You are here

SoEmbedFilter.php in Simple oEmbed 8.2

Same filename and directory in other branches
  1. 8 src/Plugin/Filter/SoEmbedFilter.php

File

src/Plugin/Filter/SoEmbedFilter.php
View source
<?php

namespace Drupal\soembed\Plugin\Filter;

use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\Url;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
use Drupal\media\IFrameUrlHelper;
use Drupal\media\OEmbed\Resource;
use Drupal\media\OEmbed\ResourceException;
use Drupal\media\OEmbed\ResourceFetcherInterface;
use Drupal\media\OEmbed\UrlResolverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a filter to embed media via oEmbed.
 *
 * @Filter(
 *   id = "filter_soembed",
 *   title = @Translation("Simple oEmbed filter"),
 *   description = @Translation("Embeds media for URL that supports oEmbed standard."),
 *   settings = {
 *     "soembed_maxwidth" = 0,
 *     "soembed_replace_inline" = FALSE
 *   },
 *   type = Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class SoEmbedFilter extends FilterBase implements ContainerFactoryPluginInterface {

  /**
   * The media settings config.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The oEmbed resource fetcher.
   *
   * @var \Drupal\media\OEmbed\ResourceFetcherInterface
   */
  protected $resourceFetcher;

  /**
   * The oEmbed URL resolver service.
   *
   * @var \Drupal\media\OEmbed\UrlResolverInterface
   */
  protected $urlResolver;

  /**
   * The iFrame URL helper service.
   *
   * @var \Drupal\media\IFrameUrlHelper
   */
  protected $iFrameUrlHelper;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * Constructs a new OEmbed instance.
   *
   * @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.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   The logger factory service.
   * @param \Drupal\media\OEmbed\ResourceFetcherInterface $resource_fetcher
   *   The oEmbed resource fetcher service.
   * @param \Drupal\media\OEmbed\UrlResolverInterface $url_resolver
   *   The oEmbed URL resolver service.
   * @param \Drupal\media\IFrameUrlHelper $iframe_url_helper
   *   The iFrame URL helper service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory, ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver, IFrameUrlHelper $iframe_url_helper, RendererInterface $renderer) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->config = $config_factory
      ->get('media.settings');
    $this->logger = $logger_factory
      ->get('media');
    $this->resourceFetcher = $resource_fetcher;
    $this->urlResolver = $url_resolver;
    $this->iFrameUrlHelper = $iframe_url_helper;
    $this->renderer = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('config.factory'), $container
      ->get('logger.factory'), $container
      ->get('media.oembed.resource_fetcher'), $container
      ->get('media.oembed.url_resolver'), $container
      ->get('media.oembed.iframe_url_helper'), $container
      ->get('renderer'));
  }

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    $lines = explode("\n", $text);
    if (!empty($this->settings['soembed_replace_inline'])) {
      $lines = preg_replace_callback('#([^"])(https?://[^\\s<]+)([^"])#', [
        $this,
        'embed',
      ], $lines);
    }
    else {
      $lines = preg_replace_callback('#^(<p>)?(https?://\\S+?)(</p>)?$#', [
        $this,
        'embed',
      ], $lines);
    }
    $text = implode("\n", $lines);
    return new FilterProcessResult($text);
  }

  /**
   * Turn URL into iframe via oEmbed.
   *
   * Most code copied from Drupal\media\Plugin\Field\FieldFormatter::viewElements().
   */
  private function embed($match) {
    $value = $match[2];
    $max_width = $this->settings['soembed_maxwidth'];
    $max_height = 0;
    try {
      $resource_url = $this->urlResolver
        ->getResourceUrl($value, $max_width, $max_height);
      $resource = $this->resourceFetcher
        ->fetchResource($resource_url);
    } catch (ResourceException $exception) {
      $this->logger
        ->error("Could not retrieve the remote URL (@url).", [
        '@url' => $value,
      ]);
      return $match[0];
    }
    if ($resource
      ->getType() === Resource::TYPE_LINK) {
      $build = [
        '#title' => $resource
          ->getTitle(),
        '#type' => 'link',
        '#url' => Url::fromUri($value),
      ];
    }
    elseif ($resource
      ->getType() === Resource::TYPE_PHOTO) {
      $build = [
        '#theme' => 'image',
        '#uri' => $resource
          ->getUrl()
          ->toString(),
        '#width' => $max_width ?: $resource
          ->getWidth(),
        '#height' => $max_height ?: $resource
          ->getHeight(),
      ];
    }
    else {
      $url = Url::fromRoute('media.oembed_iframe', [], [
        'query' => [
          'url' => $value,
          'max_width' => $max_width,
          'max_height' => $max_height,
          'hash' => $this->iFrameUrlHelper
            ->getHash($value, $max_width, $max_height),
        ],
      ]);
      $domain = $this->config
        ->get('iframe_domain');
      if ($domain) {
        $url
          ->setOption('base_url', $domain);
      }

      // Render videos and rich content in an iframe for security reasons.
      // @see: https://oembed.com/#section3
      $build = [
        '#type' => 'html_tag',
        '#tag' => 'iframe',
        '#attributes' => [
          'src' => $url
            ->toString(),
          'frameborder' => 0,
          'scrolling' => FALSE,
          'allowtransparency' => TRUE,
          'width' => $max_width ?: $resource
            ->getWidth(),
          'height' => $max_height ?: $resource
            ->getHeight(),
          'class' => [
            'media-oembed-content',
          ],
        ],
        '#attached' => [
          'library' => [
            'media/oembed.formatter',
          ],
        ],
      ];

      // An empty title attribute will disable title inheritance, so only
      // add it if the resource has a title.
      $title = $resource
        ->getTitle();
      if ($title) {
        $build['#attributes']['title'] = $title;
      }
      CacheableMetadata::createFromObject($resource)
        ->addCacheTags($this->config
        ->getCacheTags())
        ->applyTo($build);
    }
    return $match[1] . $this->renderer
      ->render($build) . $match[3];
  }

  /**
   * Define settings for text filter.
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form['soembed_maxwidth'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Maximum width of media embed'),
      '#default_value' => $this->settings['soembed_maxwidth'],
      '#description' => $this
        ->t('Leave to zero to use original values.'),
    ];
    $form['soembed_replace_inline'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Replace in-line URLs'),
      '#default_value' => $this->settings['soembed_replace_inline'],
      '#description' => $this
        ->t('If this option is checked, the filter will recognize URLs even when they are not on their own line.'),
    ];
    return $form;
  }

}

Classes

Namesort descending Description
SoEmbedFilter Provides a filter to embed media via oEmbed.