diff --git a/core/modules/media/config/install/media.settings.yml b/core/modules/media/config/install/media.settings.yml
index 853e575c671..0bdd0ce7da9 100644
--- a/core/modules/media/config/install/media.settings.yml
+++ b/core/modules/media/config/install/media.settings.yml
@@ -1 +1,2 @@
icon_base_uri: 'public://media-icons/generic'
+oembed_providers: 'https://oembed.com/providers.json'
diff --git a/core/modules/media/config/schema/media.schema.yml b/core/modules/media/config/schema/media.schema.yml
index b9156b23f86..550957d44eb 100644
--- a/core/modules/media/config/schema/media.schema.yml
+++ b/core/modules/media/config/schema/media.schema.yml
@@ -5,6 +5,12 @@ media.settings:
icon_base_uri:
type: string
label: 'Full URI to a folder where the media icons will be installed'
+ iframe_domain:
+ type: string
+ label: 'Domain from which to serve oEmbed content in an iframe'
+ oembed_providers:
+ type: string
+ label: 'The URL of the oEmbed providers database in JSON format'
media.type.*:
type: config_entity
@@ -40,6 +46,21 @@ field.formatter.settings.media_thumbnail:
type: field.formatter.settings.image
label: 'Media thumbnail field display format settings'
+field.formatter.settings.oembed:
+ type: mapping
+ label: 'oEmbed display format settings'
+ mapping:
+ max_width:
+ type: integer
+ label: 'Maximum width'
+ max_height:
+ type: integer
+ label: 'Maximum height'
+
+field.widget.settings.oembed_textfield:
+ type: field.widget.settings.string_textfield
+ label: 'oEmbed widget format settings'
+
media.source.*:
type: mapping
label: 'Media source settings'
@@ -60,6 +81,20 @@ media.source.video_file:
type: media.source.field_aware
label: '"Video" media source configuration'
+media.source.oembed:*:
+ type: media.source.field_aware
+ label: 'oEmbed media source configuration'
+ mapping:
+ thumbnails_uri:
+ type: uri
+ label: 'Thumbnail storage URI'
+ allowed_providers:
+ type: sequence
+ label: 'Allowed oEmbed providers'
+ sequence:
+ type: string
+ label: 'Provider name'
+
media.source.field_aware:
type: mapping
mapping:
diff --git a/core/modules/media/media.api.php b/core/modules/media/media.api.php
index 8de1c645754..93244f58a8a 100644
--- a/core/modules/media/media.api.php
+++ b/core/modules/media/media.api.php
@@ -20,6 +20,23 @@ function hook_media_source_info_alter(array &$sources) {
$sources['youtube']['label'] = t('Youtube rocks!');
}
+/**
+ * Alters an oEmbed resource URL before it is fetched.
+ *
+ * @param array $parsed_url
+ * A parsed URL, as returned by \Drupal\Component\Utility\UrlHelper::parse().
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * The oEmbed provider for the resource.
+ *
+ * @see \Drupal\media\OEmbed\UrlResolverInterface::getResourceUrl()
+ */
+function hook_oembed_resource_url_alter(array &$parsed_url, \Drupal\media\OEmbed\Provider $provider) {
+ // Always serve YouTube videos from youtube-nocookie.com.
+ if ($provider->getName() === 'YouTube') {
+ $parsed_url['path'] = str_replace('://youtube.com/', '://youtube-nocookie.com/', $parsed_url['path']);
+ }
+}
+
/**
* @} End of "addtogroup hooks".
*/
diff --git a/core/modules/media/media.info.yml b/core/modules/media/media.info.yml
index d7a96484c81..c5b85f50281 100644
--- a/core/modules/media/media.info.yml
+++ b/core/modules/media/media.info.yml
@@ -8,3 +8,4 @@ dependencies:
- drupal:file
- drupal:image
- drupal:user
+configure: media.settings
diff --git a/core/modules/media/media.install b/core/modules/media/media.install
index 90f9d99cd4d..c4ddca5d2d5 100644
--- a/core/modules/media/media.install
+++ b/core/modules/media/media.install
@@ -5,6 +5,9 @@
* Install, uninstall and update hooks for Media module.
*/
+use Drupal\Core\Url;
+use Drupal\media\MediaTypeInterface;
+use Drupal\media\Plugin\media\Source\OEmbedInterface;
use Drupal\user\RoleInterface;
use Drupal\user\Entity\Role;
@@ -75,6 +78,36 @@ function media_requirements($phase) {
}
}
}
+ elseif ($phase === 'runtime') {
+ // Check that oEmbed content is served in an iframe on a different domain,
+ // and complain if it isn't.
+ $domain = \Drupal::config('media.settings')->get('iframe_domain');
+
+ if (!\Drupal::service('media.oembed.url_resolver')->isSecure($domain)) {
+ // Find all media types which use a source plugin that implements
+ // OEmbedInterface.
+ $media_types = \Drupal::entityTypeManager()
+ ->getStorage('media_type')
+ ->loadMultiple();
+
+ $oembed_types = array_filter($media_types, function (MediaTypeInterface $media_type) {
+ return $media_type->getSource() instanceof OEmbedInterface;
+ });
+
+ if ($oembed_types) {
+ // @todo Potentially allow site administrators to suppress this warning
+ // permanently. See https://www.drupal.org/project/drupal/issues/2962753
+ // for more information.
+ $requirements['media_insecure_iframe'] = [
+ 'title' => t('Media'),
+ 'description' => t('It is potentially insecure to display oEmbed content in a frame that is served from the same domain as your main Drupal site, as this may allow execution of third-party code. You can specify a different domain for serving oEmbed content here.', [
+ ':url' => Url::fromRoute('media.settings')->setAbsolute()->toString(),
+ ]),
+ 'severity' => REQUIREMENT_WARNING,
+ ];
+ }
+ }
+ }
return $requirements;
}
@@ -120,3 +153,12 @@ function media_update_8500() {
$role->save();
}
}
+
+/**
+ * Creates the oembed_providers config setting.
+ */
+function media_update_8600() {
+ \Drupal::configFactory()->getEditable('media.settings')
+ ->set('oembed_providers', 'https://oembed.com/providers.json')
+ ->save(TRUE);
+}
diff --git a/core/modules/media/media.links.menu.yml b/core/modules/media/media.links.menu.yml
index e50c41217ba..1bf5fff37d1 100644
--- a/core/modules/media/media.links.menu.yml
+++ b/core/modules/media/media.links.menu.yml
@@ -3,3 +3,9 @@ entity.media_type.collection:
parent: system.admin_structure
description: 'Manage media types.'
route_name: entity.media_type.collection
+
+media.settings:
+ title: 'Media settings'
+ parent: system.admin_config_media
+ description: 'Manage media settings.'
+ route_name: media.settings
diff --git a/core/modules/media/media.module b/core/modules/media/media.module
index 5079f0fa9a8..2de628b9c77 100644
--- a/core/modules/media/media.module
+++ b/core/modules/media/media.module
@@ -15,6 +15,7 @@ use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\field\FieldConfigInterface;
+use Drupal\media\Plugin\media\Source\OEmbedInterface;
/**
* Implements hook_help().
@@ -72,6 +73,11 @@ function media_theme() {
'render element' => 'element',
'base hook' => 'field_multiple_value_form',
],
+ 'media_oembed' => [
+ 'variables' => [
+ 'post' => NULL,
+ ],
+ ],
];
}
@@ -92,6 +98,7 @@ function media_entity_access(EntityInterface $entity, $operation, AccountInterfa
*/
function media_theme_suggestions_media(array $variables) {
$suggestions = [];
+ /** @var \Drupal\media\MediaInterface $media */
$media = $variables['elements']['#media'];
$sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
@@ -99,6 +106,18 @@ function media_theme_suggestions_media(array $variables) {
$suggestions[] = 'media__' . $media->bundle();
$suggestions[] = 'media__' . $media->bundle() . '__' . $sanitized_view_mode;
+ $source = $media->getSource();
+ if ($source instanceof OEmbedInterface) {
+ $suggestions[] = 'media__oembed';
+
+ $provider_id = $source->getMetadata($media, 'provider_name');
+ if ($provider_id) {
+ $provider_id = \Drupal::transliteration()->transliterate($provider_id);
+ $provider_id = preg_replace('/[^a-z0-9_]+/', '_', mb_strtolower($provider_id));
+ $suggestions[] = "media__oembed__$provider_id";
+ }
+ }
+
return $suggestions;
}
diff --git a/core/modules/media/media.routing.yml b/core/modules/media/media.routing.yml
index ea0858d4629..dbf735e86d6 100644
--- a/core/modules/media/media.routing.yml
+++ b/core/modules/media/media.routing.yml
@@ -24,3 +24,19 @@ entity.media.revision:
requirements:
_access_media_revision: 'view'
media: \d+
+
+media.oembed_iframe:
+ path: '/media/oembed'
+ defaults:
+ _controller: '\Drupal\media\Controller\OEmbedIframeController::render'
+ requirements:
+ _permission: 'access content'
+ _csrf_token: 'TRUE'
+
+media.settings:
+ path: '/admin/config/media/media-settings'
+ defaults:
+ _form: '\Drupal\media\Form\MediaSettingsForm'
+ _title: 'Media settings'
+ requirements:
+ _permission: 'administer media'
diff --git a/core/modules/media/media.services.yml b/core/modules/media/media.services.yml
index f22f90a1246..0c3c54c225b 100644
--- a/core/modules/media/media.services.yml
+++ b/core/modules/media/media.services.yml
@@ -2,9 +2,17 @@ services:
plugin.manager.media.source:
class: Drupal\media\MediaSourceManager
parent: default_plugin_manager
-
access_check.media.revision:
class: Drupal\media\Access\MediaRevisionAccessCheck
arguments: ['@entity_type.manager']
tags:
- { name: access_check, applies_to: _access_media_revision }
+ media.oembed.url_resolver:
+ class: Drupal\media\OEmbed\UrlResolver
+ arguments: ['@media.oembed.provider_repository', '@media.oembed.resource_fetcher', '@http_client', '@module_handler', '@router.request_context', '@cache.default']
+ media.oembed.provider_repository:
+ class: Drupal\media\OEmbed\ProviderRepository
+ arguments: ['@http_client', '@config.factory', '@datetime.time', '@cache.default']
+ media.oembed.resource_fetcher:
+ class: Drupal\media\OEmbed\ResourceFetcher
+ arguments: ['@http_client', '@media.oembed.provider_repository', '@cache.default']
diff --git a/core/modules/media/src/Controller/OEmbedIframeController.php b/core/modules/media/src/Controller/OEmbedIframeController.php
new file mode 100644
index 00000000000..04faad0c86b
--- /dev/null
+++ b/core/modules/media/src/Controller/OEmbedIframeController.php
@@ -0,0 +1,156 @@
+resourceFetcher = $resource_fetcher;
+ $this->urlResolver = $url_resolver;
+ $this->renderer = $renderer;
+ $this->logger = $logger;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('media.oembed.resource_fetcher'),
+ $container->get('media.oembed.url_resolver'),
+ $container->get('renderer'),
+ $container->get('logger.factory')->get('media')
+ );
+ }
+
+ /**
+ * Renders an oEmbed resource.
+ *
+ * @param \Symfony\Component\HttpFoundation\Request $request
+ * The request object.
+ *
+ * @return \Symfony\Component\HttpFoundation\Response
+ * The response object.
+ *
+ * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
+ * Will be thrown when the 'url' parameter is not specified, invalid, or not
+ * external.
+ */
+ public function render(Request $request) {
+ $url = $request->query->get('url');
+ if (!$url) {
+ throw new BadRequestHttpException('url parameter not provided');
+ }
+ if (!UrlHelper::isValid($url, TRUE)) {
+ throw new BadRequestHttpException('url parameter is invalid');
+ }
+ if (!UrlHelper::isExternal($url)) {
+ throw new BadRequestHttpException('url parameter is not external');
+ }
+
+ // Return a response instead of a render array so that the frame content
+ // will not have all the blocks and page elements normally rendered by
+ // Drupal.
+ $response = new CacheableResponse();
+ $response->addCacheableDependency(Url::createFromRequest($request));
+
+ try {
+ $resource_url = $this->urlResolver->getResourceUrl($url, $request->query->getInt('max_width', NULL), $request->query->getInt('max_height', NULL));
+ $resource = $this->resourceFetcher->fetchResource($resource_url);
+
+ // Render the content in a new render context so that the cacheability
+ // metadata of the rendered HTML will be captured correctly.
+ $content = $this->renderer->executeInRenderContext(new RenderContext(), function () use ($resource) {
+ $element = [
+ '#theme' => 'media_oembed',
+ // Even though the resource HTML is untrusted, Markup::create() will
+ // create a trusted string. The only reason this is okay is because
+ // we are serving it in an iframe, which will mitigate the potential
+ // dangers of displaying third-party markup.
+ '#post' => Markup::create($resource->getHtml()),
+ ];
+ return $this->renderer->render($element);
+ });
+
+ $response->setContent($content)->addCacheableDependency($resource);
+ }
+ catch (ResourceException $e) {
+ // Prevent the response from being cached.
+ $response->setMaxAge(0);
+ // @todo Log additional information from ResourceException, to help with
+ // debugging, in https://www.drupal.org/project/drupal/issues/2972846.
+ $this->logger->error($e->getMessage());
+ }
+
+ return $response;
+ }
+
+}
diff --git a/core/modules/media/src/Form/MediaSettingsForm.php b/core/modules/media/src/Form/MediaSettingsForm.php
new file mode 100644
index 00000000000..03b2aa73429
--- /dev/null
+++ b/core/modules/media/src/Form/MediaSettingsForm.php
@@ -0,0 +1,108 @@
+urlResolver = $url_resolver;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('config.factory'),
+ $container->get('media.oembed.url_resolver')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormId() {
+ return 'media_settings_form';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function getEditableConfigNames() {
+ return ['media.settings'];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildForm(array $form, FormStateInterface $form_state) {
+ $domain = $this->config('media.settings')->get('iframe_domain');
+
+ if (!$this->urlResolver->isSecure($domain)) {
+ $message = $this->t('It is potentially insecure to display oEmbed content in a frame that is served from the same domain as your main Drupal site, as this may allow execution of third-party code. Take a look here for more information.');
+ $this->messenger()->addWarning($message);
+ }
+
+ $description = '
' . $this->t('Displaying media assets from third-party services, such as YouTube or Twitter, can be risky. This is because many of these services return arbitrary HTML to represent those assets, and that HTML may contain executable JavaScript code. If handled improperly, this can increase the risk of your site being compromised.') . '
';
+ $description .= '
' . $this->t('In order to mitigate the risks, third-party assets are displayed in an iFrame, which effectively sandboxes any executable code running inside it. For even more security, the iFrame can be served from an alternate domain (that also points to your Drupal site), which you can configure on this page. This helps safeguard cookies and other sensitive information.') . '
';
+
+ $form['security'] = [
+ '#type' => 'details',
+ '#title' => $this->t('Security'),
+ '#description' => $description,
+ '#open' => TRUE,
+ ];
+ // @todo Figure out how and if we should validate that this domain actually
+ // points back to Drupal.
+ // See https://www.drupal.org/project/drupal/issues/2965979 for more info.
+ $form['security']['iframe_domain'] = [
+ '#type' => 'url',
+ '#title' => $this->t('iFrame domain'),
+ '#size' => 40,
+ '#maxlength' => 255,
+ '#default_value' => $domain,
+ '#description' => $this->t('Enter a different domain from which to serve oEmbed content, including the http:// or https:// prefix. This domain needs to point back to this site, or existing oEmbed content may not display correctly, or at all.'),
+ ];
+
+ return parent::buildForm($form, $form_state);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitForm(array &$form, FormStateInterface $form_state) {
+ $this->config('media.settings')
+ ->set('iframe_domain', $form_state->getValue('iframe_domain'))
+ ->save();
+
+ parent::submitForm($form, $form_state);
+ }
+
+}
diff --git a/core/modules/media/src/MediaSourceBase.php b/core/modules/media/src/MediaSourceBase.php
index 1edc8584508..c01b9946ea0 100644
--- a/core/modules/media/src/MediaSourceBase.php
+++ b/core/modules/media/src/MediaSourceBase.php
@@ -301,7 +301,9 @@ abstract class MediaSourceBase extends PluginBase implements MediaSourceInterfac
* returned. Otherwise, a new, unused one is generated.
*/
protected function getSourceFieldName() {
- $base_id = 'field_media_' . $this->getPluginId();
+ // Some media sources are using a deriver, so their plugin IDs may contain
+ // a separator (usually ':') which is not allowed in field names.
+ $base_id = 'field_media_' . str_replace(static::DERIVATIVE_SEPARATOR, '_', $this->getPluginId());
$tries = 0;
$storage = $this->entityTypeManager->getStorage('field_storage_config');
diff --git a/core/modules/media/src/OEmbed/Endpoint.php b/core/modules/media/src/OEmbed/Endpoint.php
new file mode 100644
index 00000000000..38d265d5bd7
--- /dev/null
+++ b/core/modules/media/src/OEmbed/Endpoint.php
@@ -0,0 +1,176 @@
+provider = $provider;
+ $this->schemes = array_map('mb_strtolower', $schemes);
+
+ $this->formats = $formats = array_map('mb_strtolower', $formats);
+ // Assert that only the supported formats are present.
+ assert(array_diff($formats, ['json', 'xml']) == []);
+
+ // Use the first provided format to build the endpoint URL. If no formats
+ // are provided, default to JSON.
+ $this->url = str_replace('{format}', reset($this->formats) ?: 'json', $url);
+
+ if (!UrlHelper::isValid($this->url, TRUE) || !UrlHelper::isExternal($this->url)) {
+ throw new \InvalidArgumentException('oEmbed endpoint must have a valid external URL');
+ }
+
+ $this->supportsDiscovery = (bool) $supports_discovery;
+ }
+
+ /**
+ * Returns the endpoint URL.
+ *
+ * The URL will be built with the first available format. If the endpoint
+ * does not provide any formats, JSON will be used.
+ *
+ * @return string
+ * The endpoint URL.
+ */
+ public function getUrl() {
+ return $this->url;
+ }
+
+ /**
+ * Returns the provider this endpoint belongs to.
+ *
+ * @return \Drupal\media\OEmbed\Provider
+ * The provider object.
+ */
+ public function getProvider() {
+ return $this->provider;
+ }
+
+ /**
+ * Returns list of URL schemes supported by the provider.
+ *
+ * @return string[]
+ * List of schemes.
+ */
+ public function getSchemes() {
+ return $this->schemes;
+ }
+
+ /**
+ * Returns list of supported formats.
+ *
+ * @return string[]
+ * List of formats.
+ */
+ public function getFormats() {
+ return $this->formats;
+ }
+
+ /**
+ * Returns whether the provider supports oEmbed discovery.
+ *
+ * @return bool
+ * Returns TRUE if the provides discovery, otherwise FALSE.
+ */
+ public function supportsDiscovery() {
+ return $this->supportsDiscovery;
+ }
+
+ /**
+ * Tries to match a URL against the endpoint schemes.
+ *
+ * @param string $url
+ * Media item URL.
+ *
+ * @return bool
+ * TRUE if the URL matches against the endpoint schemes, otherwise FALSE.
+ */
+ public function matchUrl($url) {
+ foreach ($this->getSchemes() as $scheme) {
+ // Convert scheme into a valid regular expression.
+ $regexp = str_replace(['.', '*'], ['\.', '.*'], $scheme);
+ if (preg_match("|^$regexp$|", $url)) {
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+
+ /**
+ * Builds and returns the endpoint URL.
+ *
+ * @param string $url
+ * The canonical media URL.
+ *
+ * @return string
+ * URL of the oEmbed endpoint.
+ */
+ public function buildResourceUrl($url) {
+ $query = ['url' => $url];
+ return $this->getUrl() . '?' . UrlHelper::buildQuery($query);
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/Provider.php b/core/modules/media/src/OEmbed/Provider.php
new file mode 100644
index 00000000000..954dac1c9fd
--- /dev/null
+++ b/core/modules/media/src/OEmbed/Provider.php
@@ -0,0 +1,100 @@
+name = $name;
+ $this->url = $url;
+
+ try {
+ foreach ($endpoints as $endpoint) {
+ $endpoint += ['formats' => [], 'schemes' => [], 'discovery' => FALSE];
+ $this->endpoints[] = new Endpoint($endpoint['url'], $this, $endpoint['schemes'], $endpoint['formats'], $endpoint['discovery']);
+ }
+ }
+ catch (\InvalidArgumentException $e) {
+ // Just skip all the invalid endpoints.
+ // @todo Log the exception message to help with debugging in
+ // https://www.drupal.org/project/drupal/issues/2972846.
+ }
+
+ if (empty($this->endpoints)) {
+ throw new ProviderException('Provider @name does not define any valid endpoints.', $this);
+ }
+ }
+
+ /**
+ * Returns the provider name.
+ *
+ * @return string
+ * Name of the provider.
+ */
+ public function getName() {
+ return $this->name;
+ }
+
+ /**
+ * Returns the provider URL.
+ *
+ * @return string
+ * URL of the provider.
+ */
+ public function getUrl() {
+ return $this->url;
+ }
+
+ /**
+ * Returns the provider endpoints.
+ *
+ * @return \Drupal\media\OEmbed\Endpoint[]
+ * List of endpoints this provider exposes.
+ */
+ public function getEndpoints() {
+ return $this->endpoints;
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ProviderException.php b/core/modules/media/src/OEmbed/ProviderException.php
new file mode 100644
index 00000000000..259c939ed11
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ProviderException.php
@@ -0,0 +1,40 @@
+' if not.
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * (optional) The provider information.
+ * @param \Exception $previous
+ * (optional) The previous exception, if any.
+ */
+ public function __construct($message, Provider $provider = NULL, \Exception $previous = NULL) {
+ $this->provider = $provider;
+ $message = str_replace('@name', $provider ? $provider->getName() : '', $message);
+ parent::__construct($message, 0, $previous);
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ProviderRepository.php b/core/modules/media/src/OEmbed/ProviderRepository.php
new file mode 100644
index 00000000000..d04ac3e6e3b
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ProviderRepository.php
@@ -0,0 +1,122 @@
+httpClient = $http_client;
+ $this->providersUrl = $config_factory->get('media.settings')->get('oembed_providers');
+ $this->time = $time;
+ $this->cacheBackend = $cache_backend;
+ $this->maxAge = (int) $max_age;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getAll() {
+ $cache_id = 'media:oembed_providers';
+
+ $cached = $this->cacheGet($cache_id);
+ if ($cached) {
+ return $cached->data;
+ }
+
+ try {
+ $response = $this->httpClient->request('GET', $this->providersUrl);
+ }
+ catch (RequestException $e) {
+ throw new ProviderException("Could not retrieve the oEmbed provider database from $this->providersUrl", NULL, $e);
+ }
+
+ $providers = Json::decode((string) $response->getBody());
+
+ if (!is_array($providers) || empty($providers)) {
+ throw new ProviderException('Remote oEmbed providers database returned invalid or empty list.');
+ }
+
+ $keyed_providers = [];
+ foreach ($providers as $provider) {
+ try {
+ $name = (string) $provider['provider_name'];
+ $keyed_providers[$name] = new Provider($provider['provider_name'], $provider['provider_url'], $provider['endpoints']);
+ }
+ catch (ProviderException $e) {
+ // Just skip all the invalid providers.
+ // @todo Log the exception message to help with debugging.
+ }
+ }
+
+ $this->cacheSet($cache_id, $keyed_providers, $this->time->getCurrentTime() + $this->maxAge);
+ return $keyed_providers;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function get($provider_name) {
+ $providers = $this->getAll();
+
+ if (!isset($providers[$provider_name])) {
+ throw new \InvalidArgumentException("Unknown provider '$provider_name'");
+ }
+ return $providers[$provider_name];
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ProviderRepositoryInterface.php b/core/modules/media/src/OEmbed/ProviderRepositoryInterface.php
new file mode 100644
index 00000000000..b6e63afacba
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ProviderRepositoryInterface.php
@@ -0,0 +1,40 @@
+url = $url;
+ $this->resource = $resource;
+ parent::__construct($message, 0, $previous);
+ }
+
+ /**
+ * Gets the URL of the resource which caused the exception.
+ *
+ * @return string
+ * The URL of the resource.
+ */
+ public function getUrl() {
+ return $this->url;
+ }
+
+ /**
+ * Gets the raw resource data, if available.
+ *
+ * @return array
+ * The resource data.
+ */
+ public function getResource() {
+ return $this->resource;
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/Resource.php b/core/modules/media/src/OEmbed/Resource.php
new file mode 100644
index 00000000000..190a013eb08
--- /dev/null
+++ b/core/modules/media/src/OEmbed/Resource.php
@@ -0,0 +1,534 @@
+provider = $provider;
+ $this->title = $title;
+ $this->authorName = $author_name;
+ $this->authorUrl = $author_url;
+
+ if (isset($cache_age) && is_numeric($cache_age)) {
+ // If the cache age is too big, it can overflow the 'expire' column of
+ // database cache backends, causing SQL exceptions. To prevent that,
+ // arbitrarily limit the cache age to 5 years. That should be enough.
+ $this->cacheMaxAge = Cache::mergeMaxAges((int) $cache_age, 157680000);
+ }
+
+ if ($thumbnail_url) {
+ $this->thumbnailUrl = $thumbnail_url;
+ $this->setThumbnailDimensions($thumbnail_width, $thumbnail_height);
+ }
+ }
+
+ /**
+ * Creates a link resource.
+ *
+ * @param string $url
+ * (optional) The URL of the resource.
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * (optional) The resource provider.
+ * @param string $title
+ * (optional) A text title, describing the resource.
+ * @param string $author_name
+ * (optional) The name of the author/owner of the resource.
+ * @param string $author_url
+ * (optional) A URL for the author/owner of the resource.
+ * @param int $cache_age
+ * (optional) The suggested cache lifetime for this resource, in seconds.
+ * @param string $thumbnail_url
+ * (optional) A URL to a thumbnail image representing the resource. If this
+ * parameter is present, $thumbnail_width and $thumbnail_height must also be
+ * present.
+ * @param int $thumbnail_width
+ * (optional) The width of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_height must also be present.
+ * @param int $thumbnail_height
+ * (optional) The height of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_width must also be present.
+ *
+ * @return static
+ */
+ public static function link($url = NULL, Provider $provider = NULL, $title = NULL, $author_name = NULL, $author_url = NULL, $cache_age = NULL, $thumbnail_url = NULL, $thumbnail_width = NULL, $thumbnail_height = NULL) {
+ $resource = new static($provider, $title, $author_name, $author_url, $cache_age, $thumbnail_url, $thumbnail_width, $thumbnail_height);
+ $resource->type = self::TYPE_LINK;
+ $resource->url = $url;
+
+ return $resource;
+ }
+
+ /**
+ * Creates a photo resource.
+ *
+ * @param string $url
+ * The URL of the photo.
+ * @param int $width
+ * The width of the photo, in pixels.
+ * @param int $height
+ * The height of the photo, in pixels.
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * (optional) The resource provider.
+ * @param string $title
+ * (optional) A text title, describing the resource.
+ * @param string $author_name
+ * (optional) The name of the author/owner of the resource.
+ * @param string $author_url
+ * (optional) A URL for the author/owner of the resource.
+ * @param int $cache_age
+ * (optional) The suggested cache lifetime for this resource, in seconds.
+ * @param string $thumbnail_url
+ * (optional) A URL to a thumbnail image representing the resource. If this
+ * parameter is present, $thumbnail_width and $thumbnail_height must also be
+ * present.
+ * @param int $thumbnail_width
+ * (optional) The width of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_height must also be present.
+ * @param int $thumbnail_height
+ * (optional) The height of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_width must also be present.
+ *
+ * @return static
+ */
+ public static function photo($url, $width, $height, Provider $provider = NULL, $title = NULL, $author_name = NULL, $author_url = NULL, $cache_age = NULL, $thumbnail_url = NULL, $thumbnail_width = NULL, $thumbnail_height = NULL) {
+ if (empty($url)) {
+ throw new \InvalidArgumentException('Photo resources must provide a URL.');
+ }
+
+ $resource = static::link($url, $provider, $title, $author_name, $author_url, $cache_age, $thumbnail_url, $thumbnail_width, $thumbnail_height);
+ $resource->type = self::TYPE_PHOTO;
+ $resource->setDimensions($width, $height);
+
+ return $resource;
+ }
+
+ /**
+ * Creates a rich resource.
+ *
+ * @param string $html
+ * The HTML representation of the resource.
+ * @param int $width
+ * The width of the resource, in pixels.
+ * @param int $height
+ * The height of the resource, in pixels.
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * (optional) The resource provider.
+ * @param string $title
+ * (optional) A text title, describing the resource.
+ * @param string $author_name
+ * (optional) The name of the author/owner of the resource.
+ * @param string $author_url
+ * (optional) A URL for the author/owner of the resource.
+ * @param int $cache_age
+ * (optional) The suggested cache lifetime for this resource, in seconds.
+ * @param string $thumbnail_url
+ * (optional) A URL to a thumbnail image representing the resource. If this
+ * parameter is present, $thumbnail_width and $thumbnail_height must also be
+ * present.
+ * @param int $thumbnail_width
+ * (optional) The width of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_height must also be present.
+ * @param int $thumbnail_height
+ * (optional) The height of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_width must also be present.
+ *
+ * @return static
+ */
+ public static function rich($html, $width, $height, Provider $provider = NULL, $title = NULL, $author_name = NULL, $author_url = NULL, $cache_age = NULL, $thumbnail_url = NULL, $thumbnail_width = NULL, $thumbnail_height = NULL) {
+ if (empty($html)) {
+ throw new \InvalidArgumentException('The resource must provide an HTML representation.');
+ }
+
+ $resource = new static($provider, $title, $author_name, $author_url, $cache_age, $thumbnail_url, $thumbnail_width, $thumbnail_height);
+ $resource->type = self::TYPE_RICH;
+ $resource->html = $html;
+ $resource->setDimensions($width, $height);
+
+ return $resource;
+ }
+
+ /**
+ * Creates a video resource.
+ *
+ * @param string $html
+ * The HTML required to display the video.
+ * @param int $width
+ * The width of the video, in pixels.
+ * @param int $height
+ * The height of the video, in pixels.
+ * @param \Drupal\media\OEmbed\Provider $provider
+ * (optional) The resource provider.
+ * @param string $title
+ * (optional) A text title, describing the resource.
+ * @param string $author_name
+ * (optional) The name of the author/owner of the resource.
+ * @param string $author_url
+ * (optional) A URL for the author/owner of the resource.
+ * @param int $cache_age
+ * (optional) The suggested cache lifetime for this resource, in seconds.
+ * @param string $thumbnail_url
+ * (optional) A URL to a thumbnail image representing the resource. If this
+ * parameter is present, $thumbnail_width and $thumbnail_height must also be
+ * present.
+ * @param int $thumbnail_width
+ * (optional) The width of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_height must also be present.
+ * @param int $thumbnail_height
+ * (optional) The height of the thumbnail, in pixels. If this parameter is
+ * present, $thumbnail_url and $thumbnail_width must also be present.
+ *
+ * @return static
+ */
+ public static function video($html, $width, $height, Provider $provider = NULL, $title = NULL, $author_name = NULL, $author_url = NULL, $cache_age = NULL, $thumbnail_url = NULL, $thumbnail_width = NULL, $thumbnail_height = NULL) {
+ $resource = static::rich($html, $width, $height, $provider, $title, $author_name, $author_url, $cache_age, $thumbnail_url, $thumbnail_width, $thumbnail_height);
+ $resource->type = self::TYPE_VIDEO;
+
+ return $resource;
+ }
+
+ /**
+ * Returns the resource type.
+ *
+ * @return string
+ * The resource type. Will be one of the self::TYPE_* constants.
+ */
+ public function getType() {
+ return $this->type;
+ }
+
+ /**
+ * Returns the title of the resource.
+ *
+ * @return string|null
+ * The title of the resource, if known.
+ */
+ public function getTitle() {
+ return $this->title;
+ }
+
+ /**
+ * Returns the name of the resource author.
+ *
+ * @return string|null
+ * The name of the resource author, if known.
+ */
+ public function getAuthorName() {
+ return $this->authorName;
+ }
+
+ /**
+ * Returns the URL of the resource author.
+ *
+ * @return \Drupal\Core\Url|null
+ * The absolute URL of the resource author, or NULL if none is provided.
+ */
+ public function getAuthorUrl() {
+ return $this->authorUrl ? Url::fromUri($this->authorUrl)->setAbsolute() : NULL;
+ }
+
+ /**
+ * Returns the resource provider, if known.
+ *
+ * @return \Drupal\media\OEmbed\Provider|null
+ * The resource provider, or NULL if the provider is not known.
+ */
+ public function getProvider() {
+ return $this->provider;
+ }
+
+ /**
+ * Returns the URL of the resource's thumbnail image.
+ *
+ * @return \Drupal\Core\Url|null
+ * The absolute URL of the thumbnail image, or NULL if there isn't one.
+ */
+ public function getThumbnailUrl() {
+ return $this->thumbnailUrl ? Url::fromUri($this->thumbnailUrl)->setAbsolute() : NULL;
+ }
+
+ /**
+ * Returns the width of the resource's thumbnail image.
+ *
+ * @return int|null
+ * The thumbnail width in pixels, or NULL if there is no thumbnail.
+ */
+ public function getThumbnailWidth() {
+ return $this->thumbnailWidth;
+ }
+
+ /**
+ * Returns the height of the resource's thumbnail image.
+ *
+ * @return int|null
+ * The thumbnail height in pixels, or NULL if there is no thumbnail.
+ */
+ public function getThumbnailHeight() {
+ return $this->thumbnailHeight;
+ }
+
+ /**
+ * Returns the width of the resource.
+ *
+ * @return int|null
+ * The width of the resource in pixels, or NULL if the resource has no
+ * dimensions
+ */
+ public function getWidth() {
+ return $this->width;
+ }
+
+ /**
+ * Returns the height of the resource.
+ *
+ * @return int|null
+ * The height of the resource in pixels, or NULL if the resource has no
+ * dimensions.
+ */
+ public function getHeight() {
+ return $this->height;
+ }
+
+ /**
+ * Returns the URL of the resource. Only applies to 'photo' resources.
+ *
+ * @return \Drupal\Core\Url|null
+ * The resource URL, if it has one.
+ */
+ public function getUrl() {
+ if ($this->url) {
+ return Url::fromUri($this->url)->setAbsolute();
+ }
+ return NULL;
+ }
+
+ /**
+ * Returns the HTML representation of the resource.
+ *
+ * Only applies to 'rich' and 'video' resources.
+ *
+ * @return string|null
+ * The HTML representation of the resource, if it has one.
+ */
+ public function getHtml() {
+ return isset($this->html) ? (string) $this->html : NULL;
+ }
+
+ /**
+ * Sets the thumbnail dimensions.
+ *
+ * @param int $width
+ * The width of the resource.
+ * @param int $height
+ * The height of the resource.
+ *
+ * @throws \InvalidArgumentException
+ * If either $width or $height are not numbers greater than zero.
+ */
+ protected function setThumbnailDimensions($width, $height) {
+ $width = (int) $width;
+ $height = (int) $height;
+
+ if ($width > 0 && $height > 0) {
+ $this->thumbnailWidth = $width;
+ $this->thumbnailHeight = $height;
+ }
+ else {
+ throw new \InvalidArgumentException('The thumbnail dimensions must be numbers greater than zero.');
+ }
+ }
+
+ /**
+ * Sets the dimensions.
+ *
+ * @param int $width
+ * The width of the resource.
+ * @param int $height
+ * The height of the resource.
+ *
+ * @throws \InvalidArgumentException
+ * If either $width or $height are not numbers greater than zero.
+ */
+ protected function setDimensions($width, $height) {
+ $width = (int) $width;
+ $height = (int) $height;
+
+ if ($width > 0 && $height > 0) {
+ $this->width = $width;
+ $this->height = $height;
+ }
+ else {
+ throw new \InvalidArgumentException('The dimensions must be numbers greater than zero.');
+ }
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ResourceException.php b/core/modules/media/src/OEmbed/ResourceException.php
new file mode 100644
index 00000000000..f1911ffae21
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ResourceException.php
@@ -0,0 +1,46 @@
+resource = $resource;
+ parent::__construct($message, 0, $previous);
+ }
+
+ /**
+ * Gets the resource which caused the exception, if available.
+ *
+ * @return \Drupal\media\OEmbed\Resource|null
+ * The oEmbed resource.
+ */
+ public function getResource() {
+ return $this->resource;
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ResourceFetcher.php b/core/modules/media/src/OEmbed/ResourceFetcher.php
new file mode 100644
index 00000000000..0a0af99857c
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ResourceFetcher.php
@@ -0,0 +1,166 @@
+httpClient = $http_client;
+ $this->providers = $providers;
+ $this->cacheBackend = $cache_backend;
+ $this->useCaches = isset($cache_backend);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function fetchResource($url) {
+ $cache_id = "media:oembed_resource:$url";
+
+ $cached = $this->cacheGet($cache_id);
+ if ($cached) {
+ return $this->createResource($cached->data, $url);
+ }
+
+ try {
+ $response = $this->httpClient->get($url);
+ }
+ catch (RequestException $e) {
+ throw new RawResourceException('Could not retrieve the oEmbed resource.', $url, [], $e);
+ }
+
+ list($format) = $response->getHeader('Content-Type');
+ $content = (string) $response->getBody();
+
+ if (strstr($format, 'text/xml') || strstr($format, 'application/xml')) {
+ $encoder = new XmlEncoder();
+ $data = $encoder->decode($content, 'xml');
+ }
+ elseif (strstr($format, 'text/javascript') || strstr($format, 'application/json')) {
+ $data = Json::decode($content);
+ }
+ // If the response is neither XML nor JSON, we are in bat country.
+ else {
+ throw new RawResourceException('The fetched resource did not have a valid Content-Type header.', $url);
+ }
+
+ $this->cacheSet($cache_id, $data);
+
+ return $this->createResource($data, $url);
+ }
+
+ /**
+ * Creates a Resource object from raw resource data.
+ *
+ * @param array $data
+ * The resource data returned by the provider.
+ * @param string $url
+ * The URL of the resource.
+ *
+ * @return \Drupal\media\OEmbed\Resource
+ * A value object representing the resource.
+ *
+ * @throws \Drupal\media\OEmbed\RawResourceException
+ * If the resource cannot be created.
+ */
+ protected function createResource(array $data, $url) {
+ $data += [
+ 'title' => NULL,
+ 'author_name' => NULL,
+ 'author_url' => NULL,
+ 'provider_name' => NULL,
+ 'cache_age' => NULL,
+ 'thumbnail_url' => NULL,
+ 'thumbnail_width' => NULL,
+ 'thumbnail_height' => NULL,
+ 'width' => NULL,
+ 'height' => NULL,
+ 'url' => NULL,
+ 'html' => NULL,
+ 'version' => NULL,
+ ];
+
+ if ($data['version'] !== '1.0') {
+ throw new RawResourceException("Resource version must be '1.0'", $url, $data);
+ }
+
+ // Prepare the arguments to pass to the factory method.
+ $arguments = [
+ $data['provider_name'] ? $this->providers->get($data['provider_name']) : NULL,
+ $data['title'],
+ $data['author_name'],
+ $data['author_url'],
+ $data['cache_age'],
+ $data['thumbnail_url'],
+ $data['thumbnail_width'],
+ $data['thumbnail_height'],
+ ];
+
+ // All resource types except links are expected to have a width and height.
+ if ($data['type'] !== Resource::TYPE_LINK) {
+ array_unshift($arguments, $data['width'], $data['height']);
+ }
+
+ switch ($data['type']) {
+ case Resource::TYPE_LINK:
+ case Resource::TYPE_PHOTO:
+ array_unshift($arguments, $data['url']);
+ break;
+
+ case Resource::TYPE_RICH:
+ case Resource::TYPE_VIDEO:
+ array_unshift($arguments, $data['html']);
+ break;
+
+ default:
+ throw new RawResourceException('Unknown resource type: ' . $data['type'], $url, $data);
+ }
+
+ // The Resource object will validate the data we create it with and throw an
+ // exception if anything looks wrong. For better debugging, catch those
+ // exceptions and wrap them in a more specific and useful exception.
+ try {
+ return call_user_func_array(Resource::class . '::' . $data['type'], $arguments);
+ }
+ catch (\InvalidArgumentException $e) {
+ throw new RawResourceException($e->getMessage(), $url, $data, $e);
+ }
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/ResourceFetcherInterface.php b/core/modules/media/src/OEmbed/ResourceFetcherInterface.php
new file mode 100644
index 00000000000..b74fb6e2d9c
--- /dev/null
+++ b/core/modules/media/src/OEmbed/ResourceFetcherInterface.php
@@ -0,0 +1,32 @@
+providers = $providers;
+ $this->resourceFetcher = $resource_fetcher;
+ $this->httpClient = $http_client;
+ $this->moduleHandler = $module_handler;
+ $this->requestContext = $request_context;
+ $this->cacheBackend = $cache_backend;
+ $this->useCaches = isset($cache_backend);
+ }
+
+ /**
+ * Runs oEmbed discovery and returns the endpoint URL if successful.
+ *
+ * @param string $url
+ * The resource's URL.
+ *
+ * @return string|bool
+ * URL of the oEmbed endpoint, or FALSE if the discovery was unsuccessful.
+ *
+ * @throws \Drupal\media\OEmbed\RawResourceException
+ * If the resource cannot be retrieved.
+ */
+ protected function discoverResourceUrl($url) {
+ try {
+ $response = $this->httpClient->get($url);
+ }
+ catch (RequestException $e) {
+ throw new RawResourceException('Could not fetch oEmbed resource.', $url, [], $e);
+ }
+
+ $document = Html::load((string) $response->getBody());
+ $xpath = new \DOMXpath($document);
+
+ return $this->findUrl($xpath, 'json') ?: $this->findUrl($xpath, 'xml');
+ }
+
+ /**
+ * Tries to find the oEmbed URL in a DOM.
+ *
+ * @param \DOMXPath $xpath
+ * Page HTML as DOMXPath.
+ * @param string $format
+ * Format of oEmbed resource. Possible values are 'json' and 'xml'.
+ *
+ * @return bool|string
+ * A URL to an oEmbed resource or FALSE if not found.
+ */
+ protected function findUrl(\DOMXPath $xpath, $format) {
+ $result = $xpath->query("//link[@type='application/$format+oembed']");
+ return $result->length ? $result->item(0)->getAttribute('href') : FALSE;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getProviderByUrl($url) {
+ // Check the URL against every scheme of every endpoint of every provider
+ // until we find a match.
+ foreach ($this->providers->getAll() as $provider_name => $provider_info) {
+ foreach ($provider_info->getEndpoints() as $endpoint) {
+ if ($endpoint->matchUrl($url)) {
+ return $provider_info;
+ }
+ }
+ }
+
+ $resource_url = $this->discoverResourceUrl($url);
+ if ($resource_url) {
+ return $this->resourceFetcher->fetchResource($resource_url)->getProvider();
+ }
+
+ throw new RawResourceException('No matching provider found.', $url);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getResourceUrl($url, $max_width = NULL, $max_height = NULL) {
+ // Try to get the resource URL from the static cache.
+ if (isset($this->urlCache[$url])) {
+ return $this->urlCache[$url];
+ }
+
+ // Try to get the resource URL from the persistent cache.
+ $cache_id = "media:oembed_resource_url:$url:$max_width:$max_height";
+
+ $cached = $this->cacheGet($cache_id);
+ if ($cached) {
+ $this->urlCache[$url] = $cached->data;
+ return $this->urlCache[$url];
+ }
+
+ $provider = $this->getProviderByUrl($url);
+ $endpoints = $provider->getEndpoints();
+ $endpoint = reset($endpoints);
+ $resource_url = $endpoint->buildResourceUrl($url);
+
+ $parsed_url = UrlHelper::parse($resource_url);
+ if ($max_width) {
+ $parsed_url['query']['maxwidth'] = $max_width;
+ }
+ if ($max_height) {
+ $parsed_url['query']['maxheight'] = $max_height;
+ }
+ // Let other modules alter the resource URL, because some oEmbed providers
+ // provide extra parameters in the query string. For example, Instagram also
+ // supports the 'omitscript' parameter.
+ $this->moduleHandler->alter('oembed_resource_url', $parsed_url, $provider);
+ $resource_url = $parsed_url['path'] . '?' . UrlHelper::buildQuery($parsed_url['query']);
+
+ $this->urlCache[$url] = $resource_url;
+ $this->cacheSet($cache_id, $resource_url);
+
+ return $resource_url;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isSecure($url) {
+ if (!$url) {
+ return FALSE;
+ }
+ $url_host = parse_url($url, PHP_URL_HOST);
+ $system_host = parse_url($this->requestContext->getCompleteBaseUrl(), PHP_URL_HOST);
+
+ // The URL is secure if its domain is not the same as the domain of the base
+ // URL of the current request.
+ return $url_host && $system_host && $url_host !== $system_host;
+ }
+
+}
diff --git a/core/modules/media/src/OEmbed/UrlResolverInterface.php b/core/modules/media/src/OEmbed/UrlResolverInterface.php
new file mode 100644
index 00000000000..ad038f069cc
--- /dev/null
+++ b/core/modules/media/src/OEmbed/UrlResolverInterface.php
@@ -0,0 +1,54 @@
+messenger = $messenger;
+ $this->resourceFetcher = $resource_fetcher;
+ $this->urlResolver = $url_resolver;
+ $this->logger = $logger_factory->get('media');
+ $this->config = $config_factory->get('media.settings');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+ return new static(
+ $plugin_id,
+ $plugin_definition,
+ $configuration['field_definition'],
+ $configuration['settings'],
+ $configuration['label'],
+ $configuration['view_mode'],
+ $configuration['third_party_settings'],
+ $container->get('messenger'),
+ $container->get('media.oembed.resource_fetcher'),
+ $container->get('media.oembed.url_resolver'),
+ $container->get('logger.factory'),
+ $container->get('config.factory')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function defaultSettings() {
+ return [
+ 'max_width' => 0,
+ 'max_height' => 0,
+ ] + parent::defaultSettings();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function viewElements(FieldItemListInterface $items, $langcode) {
+ $element = [];
+ $max_width = $this->getSetting('max_width');
+ $max_height = $this->getSetting('max_height');
+
+ foreach ($items as $delta => $item) {
+ $main_property = $item->getFieldDefinition()->getFieldStorageDefinition()->getMainPropertyName();
+ $value = $item->{$main_property};
+
+ if (empty($value)) {
+ continue;
+ }
+
+ 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]);
+ continue;
+ }
+
+ if ($resource->getType() === Resource::TYPE_LINK) {
+ $element[$delta] = [
+ '#title' => $resource->getTitle(),
+ '#type' => 'link',
+ '#url' => Url::fromUri($value),
+ ];
+ }
+ elseif ($resource->getType() === Resource::TYPE_PHOTO) {
+ $element[$delta] = [
+ '#theme' => 'image',
+ '#uri' => $resource->getUrl()->toString(),
+ '#width' => $max_width ?: $resource->getWidth(),
+ '#height' => $max_height ?: $resource->getHeight(),
+ ];
+ }
+ else {
+ $url = Url::fromRoute('media.oembed_iframe', [
+ 'url' => $value,
+ 'max_width' => $max_width,
+ 'max_height' => $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
+ $element[$delta] = [
+ '#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(),
+ ],
+ ];
+
+ CacheableMetadata::createFromObject($resource)
+ ->addCacheTags($this->config->getCacheTags())
+ ->applyTo($element[$delta]);
+ }
+ }
+ return $element;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function settingsForm(array $form, FormStateInterface $form_state) {
+ return parent::settingsForm($form, $form_state) + [
+ 'max_width' => [
+ '#type' => 'number',
+ '#title' => $this->t('Maximum width'),
+ '#default_value' => $this->getSetting('max_width'),
+ '#size' => 5,
+ '#maxlength' => 5,
+ '#field_suffix' => $this->t('pixels'),
+ '#min' => 0,
+ ],
+ 'max_height' => [
+ '#type' => 'number',
+ '#title' => $this->t('Maximum height'),
+ '#default_value' => $this->getSetting('max_height'),
+ '#size' => 5,
+ '#maxlength' => 5,
+ '#field_suffix' => $this->t('pixels'),
+ '#min' => 0,
+ ],
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function settingsSummary() {
+ $summary = parent::settingsSummary();
+ if ($this->getSetting('max_width') && $this->getSetting('max_height')) {
+ $summary[] = $this->t('Maximum size: %max_width x %max_height pixels', [
+ '%max_width' => $this->getSetting('max_width'),
+ '%max_height' => $this->getSetting('max_height'),
+ ]);
+ }
+ elseif ($this->getSetting('max_width')) {
+ $summary[] = $this->t('Maximum width: %max_width pixels', [
+ '%max_width' => $this->getSetting('max_width'),
+ ]);
+ }
+ elseif ($this->getSetting('max_height')) {
+ $summary[] = $this->t('Maximum height: %max_height pixels', [
+ '%max_height' => $this->getSetting('max_height'),
+ ]);
+ }
+ return $summary;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function isApplicable(FieldDefinitionInterface $field_definition) {
+ $applicable = parent::isApplicable($field_definition);
+
+ if ($field_definition->getTargetEntityTypeId() !== 'media') {
+ return FALSE;
+ }
+ $media_type = MediaType::load($field_definition->getTargetBundle());
+ return $applicable && $media_type && $media_type->getSource() instanceof OEmbedInterface;
+ }
+
+}
diff --git a/core/modules/media/src/Plugin/Field/FieldWidget/OEmbedWidget.php b/core/modules/media/src/Plugin/Field/FieldWidget/OEmbedWidget.php
new file mode 100644
index 00000000000..4af0ae07b09
--- /dev/null
+++ b/core/modules/media/src/Plugin/Field/FieldWidget/OEmbedWidget.php
@@ -0,0 +1,64 @@
+getEntity()->getSource();
+ $message = $this->t('You can link to media from the following services: @providers', ['@providers' => implode(', ', $source->getAllowedProviderNames())]);
+
+ if (!empty($element['#value']['#description'])) {
+ $element['value']['#description'] = [
+ '#theme' => 'item_list',
+ '#items' => [$element['value']['#description'], $message],
+ ];
+ }
+ else {
+ $element['value']['#description'] = $message;
+ }
+
+ return $element;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function isApplicable(FieldDefinitionInterface $field_definition) {
+ $target_bundle = $field_definition->getTargetBundle();
+
+ if (!parent::isApplicable($field_definition) || $field_definition->getTargetEntityTypeId() !== 'media' || !$target_bundle) {
+ return FALSE;
+ }
+ return MediaType::load($target_bundle)->getSource() instanceof OEmbedInterface;
+ }
+
+}
diff --git a/core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraint.php b/core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraint.php
new file mode 100644
index 00000000000..306353c02d2
--- /dev/null
+++ b/core/modules/media/src/Plugin/Validation/Constraint/OEmbedResourceConstraint.php
@@ -0,0 +1,50 @@
+urlResolver = $url_resolver;
+ $this->resourceFetcher = $resource_fetcher;
+ $this->logger = $logger_factory->get('media');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container) {
+ return new static(
+ $container->get('media.oembed.url_resolver'),
+ $container->get('media.oembed.resource_fetcher'),
+ $container->get('logger.factory')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validate($value, Constraint $constraint) {
+ /** @var \Drupal\media\MediaInterface $media */
+ $media = $value->getEntity();
+ /** @var \Drupal\media\Plugin\media\Source\OEmbedInterface $source */
+ $source = $media->getSource();
+
+ if (!($source instanceof OEmbedInterface)) {
+ throw new \LogicException('Media source must implement ' . OEmbedInterface::class);
+ }
+ $url = $source->getSourceFieldValue($media);
+
+ // Ensure that the URL matches a provider.
+ try {
+ $provider = $this->urlResolver->getProviderByUrl($url);
+ }
+ catch (ResourceException $e) {
+ $this->handleException($e, $constraint->unknownProviderMessage);
+ return;
+ }
+ catch (ProviderException $e) {
+ $this->handleException($e, $constraint->providerErrorMessage);
+ return;
+ }
+
+ // Ensure that the provider is allowed.
+ if (!in_array($provider->getName(), $source->getAllowedProviderNames(), TRUE)) {
+ $this->context->addViolation($constraint->disallowedProviderMessage, [
+ '@name' => $provider->getName(),
+ ]);
+ return;
+ }
+
+ // Verify that resource fetching works, because some URLs might match
+ // the schemes but don't support oEmbed.
+ try {
+ $endpoints = $provider->getEndpoints();
+ $resource_url = reset($endpoints)->buildResourceUrl($url);
+ $this->resourceFetcher->fetchResource($resource_url);
+ }
+ catch (ResourceException $e) {
+ $this->handleException($e, $constraint->invalidResourceMessage);
+ }
+ }
+
+ /**
+ * Handles exceptions that occur during validation.
+ *
+ * @param \Exception $e
+ * The caught exception.
+ * @param string $error_message
+ * (optional) The error message to set as a constraint violation.
+ */
+ protected function handleException(\Exception $e, $error_message = NULL) {
+ if ($error_message) {
+ $this->context->addViolation($error_message);
+ }
+ // @todo If $e is a ProviderException or ResourceException, log additional
+ // debugging information contained in those exceptions in
+ // https://www.drupal.org/project/drupal/issues/2972846.
+ $this->logger->error($e->getMessage());
+ }
+
+}
diff --git a/core/modules/media/src/Plugin/media/Source/OEmbed.php b/core/modules/media/src/Plugin/media/Source/OEmbed.php
new file mode 100644
index 00000000000..af2e7e05b9b
--- /dev/null
+++ b/core/modules/media/src/Plugin/media/Source/OEmbed.php
@@ -0,0 +1,452 @@
+ 'artwork',
+ * 'label' => t('Artwork'),
+ * 'description' => t('Use artwork from Flickr and DeviantArt.'),
+ * 'allowed_field_types' => ['string'],
+ * 'default_thumbnail_filename' => 'no-thumbnail.png',
+ * 'supported_providers' => ['Deviantart.com', 'Flickr'],
+ * 'class' => 'Drupal\media\Plugin\media\Source\OEmbed',
+ * ];
+ * }
+ * @endcode
+ * The "Deviantart.com" and "Flickr" provider names are specified in
+ * https://oembed.com/providers.json. The
+ * \Drupal\media\Plugin\media\Source\OEmbed class already knows how to handle
+ * standard interactions with third-party oEmbed APIs, so there is no need to
+ * define a new class which extends it. With the code above, you will able to
+ * create media types which use the "Artwork" source plugin, and use those media
+ * types to link to assets on Deviantart and Flickr.
+ *
+ * @MediaSource(
+ * id = "oembed",
+ * label = @Translation("oEmbed source"),
+ * description = @Translation("Use oEmbed URL for reusable media."),
+ * allowed_field_types = {"string"},
+ * default_thumbnail_filename = "no-thumbnail.png",
+ * deriver = "Drupal\media\Plugin\media\Source\OEmbedDeriver",
+ * supported_providers = {},
+ * )
+ */
+class OEmbed extends MediaSourceBase implements OEmbedInterface {
+
+ /**
+ * The logger channel for media.
+ *
+ * @var \Drupal\Core\Logger\LoggerChannelInterface
+ */
+ protected $logger;
+
+ /**
+ * The messenger service.
+ *
+ * @var \Drupal\Core\Messenger\MessengerInterface
+ */
+ protected $messenger;
+
+ /**
+ * The HTTP client.
+ *
+ * @var \GuzzleHttp\Client
+ */
+ protected $httpClient;
+
+ /**
+ * The oEmbed resource fetcher service.
+ *
+ * @var \Drupal\media\OEmbed\ResourceFetcherInterface
+ */
+ protected $resourceFetcher;
+
+ /**
+ * The OEmbed manager service.
+ *
+ * @var \Drupal\media\OEmbed\UrlResolverInterface
+ */
+ protected $urlResolver;
+
+ /**
+ * 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\Entity\EntityTypeManagerInterface $entity_type_manager
+ * The entity type manager service.
+ * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
+ * The entity field manager service.
+ * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
+ * The config factory service.
+ * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
+ * The field type plugin manager service.
+ * @param \Drupal\Core\Logger\LoggerChannelInterface $logger
+ * The logger channel for media.
+ * @param \Drupal\Core\Messenger\MessengerInterface $messenger
+ * The messenger service.
+ * @param \GuzzleHttp\ClientInterface $http_client
+ * The HTTP client.
+ * @param \Drupal\media\OEmbed\ResourceFetcherInterface $resource_fetcher
+ * The oEmbed resource fetcher service.
+ * @param \Drupal\media\OEmbed\UrlResolverInterface $url_resolver
+ * The oEmbed URL resolver service.
+ */
+ public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, FieldTypePluginManagerInterface $field_type_manager, LoggerChannelInterface $logger, MessengerInterface $messenger, ClientInterface $http_client, ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver) {
+ parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
+ $this->logger = $logger;
+ $this->messenger = $messenger;
+ $this->httpClient = $http_client;
+ $this->resourceFetcher = $resource_fetcher;
+ $this->urlResolver = $url_resolver;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+ return new static(
+ $configuration,
+ $plugin_id,
+ $plugin_definition,
+ $container->get('entity_type.manager'),
+ $container->get('entity_field.manager'),
+ $container->get('config.factory'),
+ $container->get('plugin.manager.field.field_type'),
+ $container->get('logger.factory')->get('media'),
+ $container->get('messenger'),
+ $container->get('http_client'),
+ $container->get('media.oembed.resource_fetcher'),
+ $container->get('media.oembed.url_resolver')
+ );
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getMetadataAttributes() {
+ return [
+ 'type' => $this->t('Resource type'),
+ 'title' => $this->t('Resource title'),
+ 'author_name' => $this->t('The name of the author/owner'),
+ 'author_url' => $this->t('The URL of the author/owner'),
+ 'provider_name' => $this->t("The name of the provider"),
+ 'provider_url' => $this->t('The URL of the provider'),
+ 'cache_age' => $this->t('Suggested cache lifetime'),
+ 'thumbnail_url' => $this->t('The remote URL of the thumbnail'),
+ 'thumbnail_local_uri' => $this->t('The local URI of the thumbnail'),
+ 'thumbnail_local' => $this->t('The local URL of the thumbnail'),
+ 'thumbnail_width' => $this->t('Thumbnail width'),
+ 'thumbnail_height' => $this->t('Thumbnail height'),
+ 'url' => $this->t('The source URL of the resource'),
+ 'width' => $this->t('The width of the resource'),
+ 'height' => $this->t('The height of the resource'),
+ 'html' => $this->t('The HTML representation of the resource'),
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getMetadata(MediaInterface $media, $name) {
+ $media_url = $this->getSourceFieldValue($media);
+
+ try {
+ $resource_url = $this->urlResolver->getResourceUrl($media_url);
+ $resource = $this->resourceFetcher->fetchResource($resource_url);
+ }
+ catch (ResourceException $e) {
+ $this->messenger->addError($e->getMessage());
+ return NULL;
+ }
+
+ switch ($name) {
+ case 'thumbnail_local':
+ $local_uri = $this->getMetadata($media, 'thumbnail_local_uri');
+
+ if ($local_uri) {
+ if (file_exists($local_uri)) {
+ return $local_uri;
+ }
+ else {
+ try {
+ $response = $this->httpClient->get($this->getMetadata($media, 'thumbnail_url'));
+ if ($response->getStatusCode() === 200) {
+ return file_unmanaged_save_data((string) $response->getBody(), $local_uri, FILE_EXISTS_REPLACE) ?: NULL;
+ }
+ }
+ catch (RequestException $e) {
+ $this->logger->warning($e->getMessage());
+ // Return NULL so the default image will be used.
+ }
+ }
+ }
+ return NULL;
+
+ case 'thumbnail_local_uri':
+ return $this->getLocalImageUri($media);
+
+ case 'default_name':
+ if ($title = $this->getMetadata($media, 'title')) {
+ return $title;
+ }
+ elseif ($url = $this->getMetadata($media, 'url')) {
+ return $url;
+ }
+ return parent::getMetadata($media, 'default_name');
+
+ case 'thumbnail_uri':
+ return $this->getMetadata($media, 'thumbnail_local') ?: parent::getMetadata($media, 'thumbnail_uri');
+
+ case 'type':
+ return $resource->getType();
+
+ case 'title':
+ return $resource->getTitle();
+
+ case 'author_name':
+ return $resource->getAuthorName();
+
+ case 'author_url':
+ return $resource->getAuthorUrl();
+
+ case 'provider_name':
+ $provider = $resource->getProvider();
+ return $provider ? $provider->getName() : '';
+
+ case 'provider_url':
+ $provider = $resource->getProvider();
+ return $provider ? $provider->getUrl() : NULL;
+
+ case 'cache_age':
+ return $resource->getCacheMaxAge();
+
+ case 'thumbnail_url':
+ $thumbnail_url = $resource->getThumbnailUrl();
+ return $thumbnail_url ? $thumbnail_url->toString() : NULL;
+
+ case 'thumbnail_width':
+ return $resource->getThumbnailWidth();
+
+ case 'thumbnail_height':
+ return $resource->getThumbnailHeight();
+
+ case 'url':
+ $url = $resource->getUrl();
+ return $url ? $url->toString() : NULL;
+
+ case 'width':
+ return $resource->getWidth();
+
+ case 'height':
+ return $resource->getHeight();
+
+ case 'html':
+ return $resource->getHtml();
+
+ default:
+ break;
+ }
+ return NULL;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
+ $form = parent::buildConfigurationForm($form, $form_state);
+
+ $domain = $this->configFactory->get('media.settings')->get('iframe_domain');
+ if (!$this->urlResolver->isSecure($domain)) {
+ array_unshift($form, [
+ '#markup' => '
' . $this->t('It is potentially insecure to display oEmbed content in a frame that is served from the same domain as your main Drupal site, as this may allow execution of third-party code. You can specify a different domain for serving oEmbed content here (opens in a new window).', [
+ ':url' => Url::fromRoute('media.settings')->setAbsolute()->toString(),
+ ]) . '
',
+ ]);
+ }
+
+ $form['thumbnails_uri'] = [
+ '#type' => 'textfield',
+ '#title' => $this->t('Thumbnails location'),
+ '#default_value' => $this->configuration['thumbnails_uri'],
+ '#description' => $this->t('Thumbnails will be fetched from the provider for local usage. This is the location where they will be placed.'),
+ '#required' => TRUE,
+ ];
+
+ $configuration = $this->getConfiguration();
+ $plugin_definition = $this->getPluginDefinition();
+
+ $form['allowed_providers'] = [
+ '#type' => 'checkboxes',
+ '#title' => $this->t('Allowed providers'),
+ '#default_value' => $configuration['allowed_providers'],
+ '#options' => array_combine($plugin_definition['supported_providers'], $plugin_definition['supported_providers']),
+ '#description' => $this->t('Optionally select the allowed oEmbed providers for this media type. If left blank, all providers will be allowed.'),
+ ];
+ return $form;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
+ parent::submitConfigurationForm($form, $form_state);
+ $configuration = $this->getConfiguration();
+ $configuration['allowed_providers'] = array_filter(array_values($configuration['allowed_providers']));
+ $this->setConfiguration($configuration);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
+ $thumbnails_uri = $form_state->getValue('thumbnails_uri');
+ if (!file_valid_uri($thumbnails_uri)) {
+ $form_state->setErrorByName('thumbnails_uri', $this->t('@path is not a valid path.', ['@path' => $thumbnails_uri]));
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function defaultConfiguration() {
+ return [
+ 'thumbnails_uri' => 'public://oembed_thumbnails',
+ 'allowed_providers' => [],
+ ] + parent::defaultConfiguration();
+ }
+
+ /**
+ * Computes the destination URI for a thumbnail.
+ *
+ * @param \Drupal\media\MediaInterface $media
+ * A media item.
+ *
+ * @return string
+ * The local thumbnail URI.
+ *
+ * @todo Determine whether or not oEmbed media thumbnails should be stored
+ * locally at all, and if so, whether that functionality should be
+ * toggle-able. See https://www.drupal.org/project/drupal/issues/2962751 for
+ * more information.
+ */
+ protected function getLocalImageUri(MediaInterface $media) {
+ $remote_url = $this->getMetadata($media, 'thumbnail_url');
+ if (!$remote_url) {
+ return parent::getMetadata($media, 'thumbnail_uri');
+ }
+
+ $configuration = $this->getConfiguration();
+ $directory = $configuration['thumbnails_uri'];
+ // Ensure that the destination directory is writable. If not, log a warning
+ // and return the default thumbnail.
+ if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
+ $this->logger->warning('Could not prepare thumbnail destination directory @dir for oEmbed media.', [
+ '@dir' => $directory,
+ ]);
+ return parent::getMetadata($media, 'thumbnail_uri');
+ }
+
+ return $directory . '/' . $media->uuid() . '.' . pathinfo($remote_url, PATHINFO_EXTENSION);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getSourceFieldConstraints() {
+ return [
+ 'oembed_resource' => [],
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
+ $display->setComponent($this->getSourceFieldDefinition($type)->getName(), [
+ 'type' => 'oembed',
+ ]);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function prepareFormDisplay(MediaTypeInterface $type, EntityFormDisplayInterface $display) {
+ parent::prepareFormDisplay($type, $display);
+ $source_field = $this->getSourceFieldDefinition($type)->getName();
+
+ $display->setComponent($source_field, [
+ 'type' => 'oembed_textfield',
+ 'weight' => $display->getComponent($source_field)['weight'],
+ ]);
+ $display->removeComponent('name');
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getAllowedProviderNames() {
+ $configuration = $this->getConfiguration();
+ return $configuration['allowed_providers'] ?: $this->getSupportedProviderNames();
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getSupportedProviderNames() {
+ return $this->getPluginDefinition()['supported_providers'];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function createSourceField(MediaTypeInterface $type) {
+ $plugin_definition = $this->getPluginDefinition();
+
+ $label = (string) $this->t('@type URL', [
+ '@type' => $plugin_definition['label'],
+ ]);
+ return parent::createSourceField($type)->set('label', $label);
+ }
+
+}
diff --git a/core/modules/media/src/Plugin/media/Source/OEmbedDeriver.php b/core/modules/media/src/Plugin/media/Source/OEmbedDeriver.php
new file mode 100644
index 00000000000..e346210870c
--- /dev/null
+++ b/core/modules/media/src/Plugin/media/Source/OEmbedDeriver.php
@@ -0,0 +1,32 @@
+derivatives = [
+ 'video' => [
+ 'id' => 'video',
+ 'label' => t('Remote video'),
+ 'description' => t('Use remote video URL for reusable media.'),
+ 'supported_providers' => ['YouTube', 'Vimeo'],
+ 'default_thumbnail_filename' => 'video.png',
+ ] + $base_plugin_definition,
+ ];
+ return parent::getDerivativeDefinitions($base_plugin_definition);
+ }
+
+}
diff --git a/core/modules/media/src/Plugin/media/Source/OEmbedInterface.php b/core/modules/media/src/Plugin/media/Source/OEmbedInterface.php
new file mode 100644
index 00000000000..86a950b426d
--- /dev/null
+++ b/core/modules/media/src/Plugin/media/Source/OEmbedInterface.php
@@ -0,0 +1,30 @@
+
+
+
+ {{ post|raw }}
+
+
diff --git a/core/modules/media/tests/fixtures/oembed/photo_flickr.html b/core/modules/media/tests/fixtures/oembed/photo_flickr.html
new file mode 100644
index 00000000000..6ad06d81521
--- /dev/null
+++ b/core/modules/media/tests/fixtures/oembed/photo_flickr.html
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
diff --git a/core/modules/media/tests/fixtures/oembed/photo_flickr.json b/core/modules/media/tests/fixtures/oembed/photo_flickr.json
new file mode 100644
index 00000000000..7cdc28e0561
--- /dev/null
+++ b/core/modules/media/tests/fixtures/oembed/photo_flickr.json
@@ -0,0 +1,12 @@
+{
+ "type": "photo",
+ "title": "Druplicon FTW!",
+ "width": "88",
+ "height": "100",
+ "url": "internal:\/core\/misc\/druplicon.png",
+ "thumbnail_url": "internal:\/core\/misc\/druplicon.png",
+ "thumbnail_width": 88,
+ "thumbnail_height": 100,
+ "provider_name": "Flickr",
+ "version": "1.0"
+}
diff --git a/core/modules/media/tests/fixtures/oembed/providers.json b/core/modules/media/tests/fixtures/oembed/providers.json
new file mode 100644
index 00000000000..e618ec40fa6
--- /dev/null
+++ b/core/modules/media/tests/fixtures/oembed/providers.json
@@ -0,0 +1,61 @@
+[
+ {
+ "provider_name": "Vimeo",
+ "provider_url": "https:\/\/vimeo.com\/",
+ "endpoints": [
+ {
+ "schemes": [
+ "https:\/\/vimeo.com\/*",
+ "https:\/\/vimeo.com\/album\/*\/video\/*",
+ "https:\/\/vimeo.com\/channels\/*\/*",
+ "https:\/\/vimeo.com\/groups\/*\/videos\/*",
+ "https:\/\/vimeo.com\/ondemand\/*\/*",
+ "https:\/\/player.vimeo.com\/video\/*"
+ ],
+ "url": "https:\/\/vimeo.com\/api\/oembed.{format}",
+ "discovery": true
+ }
+ ]
+ },
+ {
+ "provider_name": "Twitter",
+ "provider_url": "http:\/\/www.twitter.com\/",
+ "endpoints": [
+ {
+ "schemes": [
+ "https:\/\/twitter.com\/*\/status\/*",
+ "https:\/\/*.twitter.com\/*\/status\/*"
+ ],
+ "url": "https:\/\/publish.twitter.com\/oembed"
+
+ }
+ ]
+ },
+ {
+ "provider_name": "CollegeHumor",
+ "provider_url": "http:\/\/www.collegehumor.com\/",
+ "endpoints": [
+ {
+ "schemes": [
+ "http:\/\/www.collegehumor.com\/video\/*"
+ ],
+ "url": "http:\/\/www.collegehumor.com\/oembed.{format}",
+ "discovery": true
+ }
+ ]
+ },
+ {
+ "provider_name": "Flickr",
+ "provider_url": "http:\/\/www.flickr.com\/",
+ "endpoints": [
+ {
+ "schemes": [
+ "http:\/\/*.flickr.com\/photos\/*",
+ "http:\/\/flic.kr\/p\/*"
+ ],
+ "url": "http:\/\/www.flickr.com\/services\/oembed\/",
+ "discovery": true
+ }
+ ]
+ }
+]
diff --git a/core/modules/media/tests/fixtures/oembed/rich_twitter.json b/core/modules/media/tests/fixtures/oembed/rich_twitter.json
new file mode 100644
index 00000000000..f27b88199f1
--- /dev/null
+++ b/core/modules/media/tests/fixtures/oembed/rich_twitter.json
@@ -0,0 +1,13 @@
+{
+ "url": "https:\/\/twitter.com\/drupaldevdays\/status\/935643039741202432",
+ "author_name": "Drupal Dev Days",
+ "author_url": "https:\/\/twitter.com\/drupaldevdays",
+ "html": "