updated core to 8.6.1 via composer
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Controller;
|
||||
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
use Drupal\Core\Cache\CacheableMetadata;
|
||||
use Drupal\Core\Cache\CacheableResponse;
|
||||
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
|
||||
use Drupal\Core\Logger\LoggerChannelInterface;
|
||||
use Drupal\Core\Render\RenderContext;
|
||||
use Drupal\Core\Render\RendererInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\media\IFrameMarkup;
|
||||
use Drupal\media\IFrameUrlHelper;
|
||||
use Drupal\media\OEmbed\ResourceException;
|
||||
use Drupal\media\OEmbed\ResourceFetcherInterface;
|
||||
use Drupal\media\OEmbed\UrlResolverInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
/**
|
||||
* Controller which renders an oEmbed resource in a bare page (without blocks).
|
||||
*
|
||||
* This controller is meant to render untrusted third-party HTML returned by
|
||||
* an oEmbed provider in an iframe, so as to mitigate the potential dangers of
|
||||
* of displaying third-party markup (i.e., XSS). The HTML returned by this
|
||||
* controller should not be trusted, and should *never* be displayed outside
|
||||
* of an iframe.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class OEmbedIframeController implements ContainerInjectionInterface {
|
||||
|
||||
/**
|
||||
* The oEmbed resource fetcher service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ResourceFetcherInterface
|
||||
*/
|
||||
protected $resourceFetcher;
|
||||
|
||||
/**
|
||||
* The oEmbed URL resolver service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\UrlResolverInterface
|
||||
*/
|
||||
protected $urlResolver;
|
||||
|
||||
/**
|
||||
* The renderer service.
|
||||
*
|
||||
* @var \Drupal\Core\Render\RendererInterface
|
||||
*/
|
||||
protected $renderer;
|
||||
|
||||
/**
|
||||
* The logger channel.
|
||||
*
|
||||
* @var \Drupal\Core\Logger\LoggerChannelInterface
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* The iFrame URL helper service.
|
||||
*
|
||||
* @var \Drupal\media\IFrameUrlHelper
|
||||
*/
|
||||
protected $iFrameUrlHelper;
|
||||
|
||||
/**
|
||||
* Constructs an OEmbedIframeController instance.
|
||||
*
|
||||
* @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\Core\Render\RendererInterface $renderer
|
||||
* The renderer service.
|
||||
* @param \Drupal\Core\Logger\LoggerChannelInterface $logger
|
||||
* The logger channel.
|
||||
* @param \Drupal\media\IFrameUrlHelper $iframe_url_helper
|
||||
* The iFrame URL helper service.
|
||||
*/
|
||||
public function __construct(ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver, RendererInterface $renderer, LoggerChannelInterface $logger, IFrameUrlHelper $iframe_url_helper) {
|
||||
$this->resourceFetcher = $resource_fetcher;
|
||||
$this->urlResolver = $url_resolver;
|
||||
$this->renderer = $renderer;
|
||||
$this->logger = $logger;
|
||||
$this->iFrameUrlHelper = $iframe_url_helper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'),
|
||||
$container->get('media.oembed.iframe_url_helper')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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\AccessDeniedHttpException
|
||||
* Will be thrown if the 'hash' parameter does not match the expected hash
|
||||
* of the 'url' parameter.
|
||||
*/
|
||||
public function render(Request $request) {
|
||||
$url = $request->query->get('url');
|
||||
$max_width = $request->query->getInt('max_width', NULL);
|
||||
$max_height = $request->query->getInt('max_height', NULL);
|
||||
|
||||
// Hash the URL and max dimensions, and ensure it is equal to the hash
|
||||
// parameter passed in the query string.
|
||||
$hash = $this->iFrameUrlHelper->getHash($url, $max_width, $max_height);
|
||||
if (!Crypt::hashEquals($hash, $request->query->get('hash', ''))) {
|
||||
throw new AccessDeniedHttpException('This resource is not available');
|
||||
}
|
||||
|
||||
// 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, $max_width, $max_height);
|
||||
$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.
|
||||
$element = [
|
||||
'#theme' => 'media_oembed_iframe',
|
||||
// Even though the resource HTML is untrusted, IFrameMarkup::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.
|
||||
'#media' => IFrameMarkup::create($resource->getHtml()),
|
||||
'#cache' => [
|
||||
// Add the 'rendered' cache tag as this response is not processed by
|
||||
// \Drupal\Core\Render\MainContent\HtmlRenderer::renderResponse().
|
||||
'tags' => ['rendered'],
|
||||
],
|
||||
];
|
||||
$content = $this->renderer->executeInRenderContext(new RenderContext(), function () use ($resource, $element) {
|
||||
return $this->renderer->render($element);
|
||||
});
|
||||
$response
|
||||
->setContent($content)
|
||||
->addCacheableDependency($resource)
|
||||
->addCacheableDependency(CacheableMetadata::createFromRenderArray($element));
|
||||
}
|
||||
catch (ResourceException $e) {
|
||||
// Prevent the response from being cached.
|
||||
$response->setMaxAge(0);
|
||||
|
||||
// The oEmbed system makes heavy use of exception wrapping, so log the
|
||||
// entire exception chain to help with troubleshooting.
|
||||
do {
|
||||
// @todo Log additional information from ResourceException, to help with
|
||||
// debugging, in https://www.drupal.org/project/drupal/issues/2972846.
|
||||
$this->logger->error($e->getMessage());
|
||||
$e = $e->getPrevious();
|
||||
} while ($e);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -29,7 +29,7 @@ use Drupal\user\UserInterface;
|
||||
* ),
|
||||
* bundle_label = @Translation("Media type"),
|
||||
* handlers = {
|
||||
* "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
|
||||
* "storage" = "Drupal\media\MediaStorage",
|
||||
* "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
|
||||
* "list_builder" = "Drupal\media\MediaListBuilder",
|
||||
* "access" = "Drupal\media\MediaAccessControlHandler",
|
||||
@@ -38,6 +38,7 @@ use Drupal\user\UserInterface;
|
||||
* "add" = "Drupal\media\MediaForm",
|
||||
* "edit" = "Drupal\media\MediaForm",
|
||||
* "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
|
||||
* "delete-multiple-confirm" = "Drupal\Core\Entity\Form\DeleteMultipleForm",
|
||||
* },
|
||||
* "translation" = "Drupal\content_translation\ContentTranslationHandler",
|
||||
* "views_data" = "Drupal\media\MediaViewsData",
|
||||
@@ -76,6 +77,7 @@ use Drupal\user\UserInterface;
|
||||
* "canonical" = "/media/{media}",
|
||||
* "collection" = "/admin/content/media",
|
||||
* "delete-form" = "/media/{media}/delete",
|
||||
* "delete-multiple-form" = "/media/delete",
|
||||
* "edit-form" = "/media/{media}/edit",
|
||||
* "revision" = "/media/{media}/revisions/{media_revision}/view",
|
||||
* }
|
||||
@@ -179,25 +181,7 @@ class Media extends EditorialContentEntityBase implements MediaInterface {
|
||||
* https://www.drupal.org/node/2878119
|
||||
*/
|
||||
protected function updateThumbnail($from_queue = FALSE) {
|
||||
$file_storage = \Drupal::service('entity_type.manager')->getStorage('file');
|
||||
$thumbnail_uri = $this->getThumbnailUri($from_queue);
|
||||
$existing = $file_storage->getQuery()
|
||||
->condition('uri', $thumbnail_uri)
|
||||
->execute();
|
||||
|
||||
if ($existing) {
|
||||
$this->thumbnail->target_id = reset($existing);
|
||||
}
|
||||
else {
|
||||
/** @var \Drupal\file\FileInterface $file */
|
||||
$file = $file_storage->create(['uri' => $thumbnail_uri]);
|
||||
if ($owner = $this->getOwner()) {
|
||||
$file->setOwner($owner);
|
||||
}
|
||||
$file->setPermanent();
|
||||
$file->save();
|
||||
$this->thumbnail->target_id = $file->id();
|
||||
}
|
||||
$this->thumbnail->target_id = $this->loadThumbnail($this->getThumbnailUri($from_queue))->id();
|
||||
|
||||
// Set the thumbnail alt.
|
||||
$media_source = $this->getSource();
|
||||
@@ -220,6 +204,52 @@ class Media extends EditorialContentEntityBase implements MediaInterface {
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the file entity for the thumbnail.
|
||||
*
|
||||
* If the file entity does not exist, it will be created.
|
||||
*
|
||||
* @param string $thumbnail_uri
|
||||
* (optional) The URI of the thumbnail, used to load or create the file
|
||||
* entity. If omitted, the default thumbnail URI will be used.
|
||||
*
|
||||
* @return \Drupal\file\FileInterface
|
||||
* The thumbnail file entity.
|
||||
*/
|
||||
protected function loadThumbnail($thumbnail_uri = NULL) {
|
||||
$values = [
|
||||
'uri' => $thumbnail_uri ?: $this->getDefaultThumbnailUri(),
|
||||
];
|
||||
|
||||
$file_storage = $this->entityTypeManager()->getStorage('file');
|
||||
|
||||
$existing = $file_storage->loadByProperties($values);
|
||||
if ($existing) {
|
||||
$file = reset($existing);
|
||||
}
|
||||
else {
|
||||
/** @var \Drupal\file\FileInterface $file */
|
||||
$file = $file_storage->create($values);
|
||||
if ($owner = $this->getOwner()) {
|
||||
$file->setOwner($owner);
|
||||
}
|
||||
$file->setPermanent();
|
||||
$file->save();
|
||||
}
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URI of the default thumbnail.
|
||||
*
|
||||
* @return string
|
||||
* The default thumbnail URI.
|
||||
*/
|
||||
protected function getDefaultThumbnailUri() {
|
||||
$default_thumbnail_filename = $this->getSource()->getPluginDefinition()['default_thumbnail_filename'];
|
||||
return \Drupal::config('media.settings')->get('icon_base_uri') . '/' . $default_thumbnail_filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the queued thumbnail for the media item.
|
||||
*
|
||||
@@ -255,17 +285,14 @@ class Media extends EditorialContentEntityBase implements MediaInterface {
|
||||
protected function getThumbnailUri($from_queue) {
|
||||
$thumbnails_queued = $this->bundle->entity->thumbnailDownloadsAreQueued();
|
||||
if ($thumbnails_queued && $this->isNew()) {
|
||||
$default_thumbnail_filename = $this->getSource()->getPluginDefinition()['default_thumbnail_filename'];
|
||||
$thumbnail_uri = \Drupal::service('config.factory')->get('media.settings')->get('icon_base_uri') . '/' . $default_thumbnail_filename;
|
||||
return $this->getDefaultThumbnailUri();
|
||||
}
|
||||
elseif ($thumbnails_queued && !$from_queue) {
|
||||
$thumbnail_uri = $this->get('thumbnail')->entity->getFileUri();
|
||||
}
|
||||
else {
|
||||
$thumbnail_uri = $this->getSource()->getMetadata($this, $this->getSource()->getPluginDefinition()['thumbnail_uri_metadata_attribute']);
|
||||
return $this->get('thumbnail')->entity->getFileUri();
|
||||
}
|
||||
|
||||
return $thumbnail_uri;
|
||||
$source = $this->getSource();
|
||||
return $source->getMetadata($this, $source->getPluginDefinition()['thumbnail_uri_metadata_attribute']);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -303,30 +330,9 @@ class Media extends EditorialContentEntityBase implements MediaInterface {
|
||||
public function preSave(EntityStorageInterface $storage) {
|
||||
parent::preSave($storage);
|
||||
|
||||
$media_source = $this->getSource();
|
||||
foreach ($this->translations as $langcode => $data) {
|
||||
if ($this->hasTranslation($langcode)) {
|
||||
$translation = $this->getTranslation($langcode);
|
||||
// Try to set fields provided by the media source and mapped in
|
||||
// media type config.
|
||||
foreach ($translation->bundle->entity->getFieldMap() as $metadata_attribute_name => $entity_field_name) {
|
||||
// Only save value in entity field if empty. Do not overwrite existing
|
||||
// data.
|
||||
if ($translation->hasField($entity_field_name) && ($translation->get($entity_field_name)->isEmpty() || $translation->hasSourceFieldChanged())) {
|
||||
$translation->set($entity_field_name, $media_source->getMetadata($translation, $metadata_attribute_name));
|
||||
}
|
||||
}
|
||||
|
||||
// Try to set a default name for this media item if no name is provided.
|
||||
if ($translation->get('name')->isEmpty()) {
|
||||
$translation->setName($translation->getName());
|
||||
}
|
||||
|
||||
// Set thumbnail.
|
||||
if ($translation->shouldUpdateThumbnail()) {
|
||||
$translation->updateThumbnail();
|
||||
}
|
||||
}
|
||||
// If no thumbnail has been explicitly set, use the default thumbnail.
|
||||
if ($this->get('thumbnail')->isEmpty()) {
|
||||
$this->thumbnail->target_id = $this->loadThumbnail()->id();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -367,6 +373,61 @@ class Media extends EditorialContentEntityBase implements MediaInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the media entity's field values from the source's metadata.
|
||||
*
|
||||
* Fetching the metadata could be slow (e.g., if requesting it from a remote
|
||||
* API), so this is called by \Drupal\media\MediaStorage::save() prior to it
|
||||
* beginning the database transaction, whereas static::preSave() executes
|
||||
* after the transaction has already started.
|
||||
*
|
||||
* @internal
|
||||
* Expose this as an API in
|
||||
* https://www.drupal.org/project/drupal/issues/2992426.
|
||||
*/
|
||||
public function prepareSave() {
|
||||
// @todo If the source plugin talks to a remote API (e.g. oEmbed), this code
|
||||
// might be performing a fair number of HTTP requests. This is dangerously
|
||||
// brittle and should probably be handled by a queue, to avoid doing HTTP
|
||||
// operations during entity save. See
|
||||
// https://www.drupal.org/project/drupal/issues/2976875 for more.
|
||||
|
||||
// In order for metadata to be mapped correctly, $this->original must be
|
||||
// set. However, that is only set once parent::save() is called, so work
|
||||
// around that by setting it here.
|
||||
if (!isset($this->original) && $id = $this->id()) {
|
||||
$this->original = $this->entityTypeManager()
|
||||
->getStorage('media')
|
||||
->loadUnchanged($id);
|
||||
}
|
||||
|
||||
$media_source = $this->getSource();
|
||||
foreach ($this->translations as $langcode => $data) {
|
||||
if ($this->hasTranslation($langcode)) {
|
||||
$translation = $this->getTranslation($langcode);
|
||||
// Try to set fields provided by the media source and mapped in
|
||||
// media type config.
|
||||
foreach ($translation->bundle->entity->getFieldMap() as $metadata_attribute_name => $entity_field_name) {
|
||||
// Only save value in entity field if empty. Do not overwrite existing
|
||||
// data.
|
||||
if ($translation->hasField($entity_field_name) && ($translation->get($entity_field_name)->isEmpty() || $translation->hasSourceFieldChanged())) {
|
||||
$translation->set($entity_field_name, $media_source->getMetadata($translation, $metadata_attribute_name));
|
||||
}
|
||||
}
|
||||
|
||||
// Try to set a default name for this media item if no name is provided.
|
||||
if ($translation->get('name')->isEmpty()) {
|
||||
$translation->setName($translation->getName());
|
||||
}
|
||||
|
||||
// Set thumbnail.
|
||||
if ($translation->shouldUpdateThumbnail($this->isNew())) {
|
||||
$translation->updateThumbnail();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
||||
@@ -100,6 +100,8 @@ class MediaType extends ConfigEntityBundleBase implements MediaTypeInterface, En
|
||||
* Whether thumbnail downloads are queued.
|
||||
*
|
||||
* @var bool
|
||||
*
|
||||
* @see \Drupal\media\MediaTypeInterface::thumbnailDownloadsAreQueued()
|
||||
*/
|
||||
protected $queue_thumbnail_downloads = FALSE;
|
||||
|
||||
@@ -113,7 +115,15 @@ class MediaType extends ConfigEntityBundleBase implements MediaTypeInterface, En
|
||||
/**
|
||||
* The media source configuration.
|
||||
*
|
||||
* A media source can provide a configuration form with source plugin-specific
|
||||
* configuration settings, which must at least include a source_field element
|
||||
* containing a the name of the source field for the media type. The source
|
||||
* configuration is defined by, and used to load, the source plugin. See
|
||||
* \Drupal\media\MediaTypeInterface for an explanation of media sources.
|
||||
*
|
||||
* @var array
|
||||
*
|
||||
* @see \Drupal\media\MediaTypeInterface::getSource()
|
||||
*/
|
||||
protected $source_configuration = [];
|
||||
|
||||
@@ -125,9 +135,11 @@ class MediaType extends ConfigEntityBundleBase implements MediaTypeInterface, En
|
||||
protected $sourcePluginCollection;
|
||||
|
||||
/**
|
||||
* Field map. Fields provided by type plugin to be stored as entity fields.
|
||||
* The metadata field map.
|
||||
*
|
||||
* @var array
|
||||
*
|
||||
* @see \Drupal\media\MediaTypeInterface::getFieldMap()
|
||||
*/
|
||||
protected $field_map = [];
|
||||
|
||||
|
||||
@@ -13,6 +13,12 @@ use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
/**
|
||||
* Provides a confirmation form to delete multiple media items at once.
|
||||
*
|
||||
* @deprecated in Drupal 8.6.x, to be removed before Drupal 9.0.0.
|
||||
* This route is not used in Drupal core. As an internal API, it may also be
|
||||
* removed in a minor release. If you are using it, copy the class
|
||||
* and the related "entity.media.multiple_delete_confirm" route to your
|
||||
* module.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class MediaDeleteMultipleConfirmForm extends ConfirmFormBase {
|
||||
@@ -47,6 +53,7 @@ class MediaDeleteMultipleConfirmForm extends ConfirmFormBase {
|
||||
* The entity type manager.
|
||||
*/
|
||||
public function __construct(PrivateTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $manager) {
|
||||
@trigger_error(__CLASS__ . ' is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. It is not used in Drupal core. As an internal API, it may also be removed in a minor release. If you are using it, copy the class and the related "entity.media.multiple_delete_confirm" route to your module.', E_USER_DEPRECATED);
|
||||
$this->tempStoreFactory = $temp_store_factory;
|
||||
$this->storage = $manager->getStorage('media');
|
||||
}
|
||||
@@ -195,7 +202,7 @@ class MediaDeleteMultipleConfirmForm extends ConfirmFormBase {
|
||||
}
|
||||
|
||||
if ($total_count) {
|
||||
drupal_set_message($this->formatPlural($total_count, 'Deleted 1 media item.', 'Deleted @count media items.'));
|
||||
$this->messenger()->addStatus($this->formatPlural($total_count, 'Deleted 1 media item.', 'Deleted @count media items.'));
|
||||
}
|
||||
|
||||
$this->tempStoreFactory->get('media_multiple_delete_confirm')->delete(\Drupal::currentUser()->id());
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Form;
|
||||
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\media\IFrameUrlHelper;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides a form to configure Media settings.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class MediaSettingsForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* The iFrame URL helper service.
|
||||
*
|
||||
* @var \Drupal\media\IFrameUrlHelper
|
||||
*/
|
||||
protected $iFrameUrlHelper;
|
||||
|
||||
/**
|
||||
* MediaSettingsForm constructor.
|
||||
*
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory service.
|
||||
* @param \Drupal\media\IFrameUrlHelper $iframe_url_helper
|
||||
* The iFrame URL helper service.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, IFrameUrlHelper $iframe_url_helper) {
|
||||
parent::__construct($config_factory);
|
||||
$this->iFrameUrlHelper = $iframe_url_helper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('config.factory'),
|
||||
$container->get('media.oembed.iframe_url_helper')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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->iFrameUrlHelper->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. <a href="https://oembed.com/#section3" target="_blank">Take a look here for more information</a>.');
|
||||
$this->messenger()->addWarning($message);
|
||||
}
|
||||
|
||||
$description = '<p>' . $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.') . '</p>';
|
||||
$description .= '<p>' . $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.') . '</p>';
|
||||
|
||||
$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 <em>http://</em> or <em>https://</em> 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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media;
|
||||
|
||||
use Drupal\Component\Render\MarkupInterface;
|
||||
use Drupal\Component\Render\MarkupTrait;
|
||||
|
||||
/**
|
||||
* Defines an object that wraps oEmbed markup for use in an iFrame.
|
||||
*
|
||||
* This object is not constructed with a known safe string as the strings come
|
||||
* from an external site. It must not be used outside the Media module's oEmbed
|
||||
* iframe rendering.
|
||||
*
|
||||
* @internal
|
||||
* This object is an internal part of the oEmbed system and should only be
|
||||
* used in \Drupal\media\Controller\OEmbedIframeController.
|
||||
*
|
||||
* @see \Drupal\media\Controller\OEmbedIframeController
|
||||
*/
|
||||
class IFrameMarkup implements MarkupInterface {
|
||||
use MarkupTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media;
|
||||
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
use Drupal\Core\PrivateKey;
|
||||
use Drupal\Core\Routing\RequestContext;
|
||||
use Drupal\Core\Site\Settings;
|
||||
|
||||
/**
|
||||
* Providers helper functions for displaying oEmbed resources in an iFrame.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class IFrameUrlHelper {
|
||||
|
||||
/**
|
||||
* The request context service.
|
||||
*
|
||||
* @var \Drupal\Core\Routing\RequestContext
|
||||
*/
|
||||
protected $requestContext;
|
||||
|
||||
/**
|
||||
* The private key service.
|
||||
*
|
||||
* @var \Drupal\Core\PrivateKey
|
||||
*/
|
||||
protected $privateKey;
|
||||
|
||||
/**
|
||||
* IFrameUrlHelper constructor.
|
||||
*
|
||||
* @param \Drupal\Core\Routing\RequestContext $request_context
|
||||
* The request context service.
|
||||
* @param \Drupal\Core\PrivateKey $private_key
|
||||
* The private key service.
|
||||
*/
|
||||
public function __construct(RequestContext $request_context, PrivateKey $private_key) {
|
||||
$this->requestContext = $request_context;
|
||||
$this->privateKey = $private_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes an oEmbed resource URL.
|
||||
*
|
||||
* @param string $url
|
||||
* The resource URL.
|
||||
* @param int $max_width
|
||||
* (optional) The maximum width of the resource.
|
||||
* @param int $max_height
|
||||
* (optional) The maximum height of the resource.
|
||||
*
|
||||
* @return string
|
||||
* The hashed URL.
|
||||
*/
|
||||
public function getHash($url, $max_width = NULL, $max_height = NULL) {
|
||||
return Crypt::hmacBase64("$url:$max_width:$max_height", $this->privateKey->get() . Settings::getHashSalt());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an oEmbed URL can be securely displayed in an frame.
|
||||
*
|
||||
* @param string $url
|
||||
* The URL to check.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the URL is considered secure, otherwise FALSE.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -47,7 +47,7 @@ class MediaAccessControlHandler extends EntityAccessControlHandler {
|
||||
if ($account->hasPermission('update media') && $is_owner) {
|
||||
return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
|
||||
}
|
||||
return AccessResult::neutral()->cachePerPermissions();
|
||||
return AccessResult::neutral("The following permissions are required: 'update any media' OR 'update own media' OR '$type: edit any media' OR '$type: edit own media'.")->cachePerPermissions();
|
||||
|
||||
case 'delete':
|
||||
if ($account->hasPermission('delete any ' . $type . ' media')) {
|
||||
@@ -64,7 +64,7 @@ class MediaAccessControlHandler extends EntityAccessControlHandler {
|
||||
if ($account->hasPermission('delete media') && $is_owner) {
|
||||
return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($entity);
|
||||
}
|
||||
return AccessResult::neutral()->cachePerPermissions();
|
||||
return AccessResult::neutral("The following permissions are required: 'delete any media' OR 'delete own media' OR '$type: delete any media' OR '$type: delete own media'.")->cachePerPermissions();
|
||||
|
||||
default:
|
||||
return AccessResult::neutral()->cachePerPermissions();
|
||||
|
||||
@@ -59,20 +59,29 @@ class MediaForm extends ContentEntityForm {
|
||||
*/
|
||||
public function save(array $form, FormStateInterface $form_state) {
|
||||
$saved = parent::save($form, $form_state);
|
||||
$context = ['@type' => $this->entity->bundle(), '%label' => $this->entity->label()];
|
||||
$context = ['@type' => $this->entity->bundle(), '%label' => $this->entity->label(), 'link' => $this->entity->toLink($this->t('View'))->toString()];
|
||||
$logger = $this->logger('media');
|
||||
$t_args = ['@type' => $this->entity->bundle->entity->label(), '%label' => $this->entity->label()];
|
||||
$t_args = ['@type' => $this->entity->bundle->entity->label(), '%label' => $this->entity->toLink($this->entity->label())->toString()];
|
||||
|
||||
if ($saved === SAVED_NEW) {
|
||||
$logger->notice('@type: added %label.', $context);
|
||||
drupal_set_message($this->t('@type %label has been created.', $t_args));
|
||||
$this->messenger()->addStatus($this->t('@type %label has been created.', $t_args));
|
||||
}
|
||||
else {
|
||||
$logger->notice('@type: updated %label.', $context);
|
||||
drupal_set_message($this->t('@type %label has been updated.', $t_args));
|
||||
$this->messenger()->addStatus($this->t('@type %label has been updated.', $t_args));
|
||||
}
|
||||
|
||||
// Redirect the user to the media overview if the user has the 'access media
|
||||
// overview' permission. If not, redirect to the canonical URL of the media
|
||||
// item.
|
||||
if ($this->currentUser()->hasPermission('access media overview')) {
|
||||
$form_state->setRedirectUrl($this->entity->toUrl('collection'));
|
||||
}
|
||||
else {
|
||||
$form_state->setRedirectUrl($this->entity->toUrl());
|
||||
}
|
||||
|
||||
$form_state->setRedirectUrl($this->entity->toUrl('canonical'));
|
||||
return $saved;
|
||||
}
|
||||
|
||||
|
||||
@@ -115,11 +115,11 @@ class MediaListBuilder extends EntityListBuilder {
|
||||
/** @var \Drupal\media\MediaInterface $entity */
|
||||
if ($this->thumbnailStyleExists) {
|
||||
$row['thumbnail'] = [];
|
||||
if ($thumbnail_url = $entity->getSource()->getMetadata($entity, 'thumbnail_uri')) {
|
||||
if ($thumbnail_uri = $entity->getSource()->getMetadata($entity, 'thumbnail_uri')) {
|
||||
$row['thumbnail']['data'] = [
|
||||
'#theme' => 'image_style',
|
||||
'#style_name' => 'thumbnail',
|
||||
'#uri' => $thumbnail_url,
|
||||
'#uri' => $thumbnail_uri,
|
||||
'#height' => 50,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media;
|
||||
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Entity\Sql\SqlContentEntityStorage;
|
||||
|
||||
/**
|
||||
* Defines the storage handler class for media.
|
||||
*
|
||||
* The default storage is overridden to handle metadata fetching outside of the
|
||||
* database transaction.
|
||||
*/
|
||||
class MediaStorage extends SqlContentEntityStorage {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function save(EntityInterface $media) {
|
||||
// For backwards compatibility, modules that override the Media entity
|
||||
// class, are not required to implement the prepareSave() method.
|
||||
// @todo For Drupal 8.7, consider throwing a deprecation notice if the
|
||||
// method doesn't exist. See
|
||||
// https://www.drupal.org/project/drupal/issues/2992426 for further
|
||||
// discussion.
|
||||
if (method_exists($media, 'prepareSave')) {
|
||||
$media->prepareSave();
|
||||
}
|
||||
return parent::save($media);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Drupal\media;
|
||||
|
||||
use Drupal\Component\Plugin\PluginManagerInterface;
|
||||
use Drupal\Core\Ajax\AjaxResponse;
|
||||
use Drupal\Core\Ajax\ReplaceCommand;
|
||||
use Drupal\Core\Entity\EntityFieldManagerInterface;
|
||||
@@ -23,7 +24,7 @@ class MediaTypeForm extends EntityForm {
|
||||
/**
|
||||
* Media source plugin manager.
|
||||
*
|
||||
* @var \Drupal\media\MediaSourceManager
|
||||
* @var \Drupal\Component\Plugin\PluginManagerInterface
|
||||
*/
|
||||
protected $sourceManager;
|
||||
|
||||
@@ -37,12 +38,12 @@ class MediaTypeForm extends EntityForm {
|
||||
/**
|
||||
* Constructs a new class instance.
|
||||
*
|
||||
* @param \Drupal\media\MediaSourceManager $source_manager
|
||||
* @param \Drupal\Component\Plugin\PluginManagerInterface $source_manager
|
||||
* Media source plugin manager.
|
||||
* @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
|
||||
* Entity field manager service.
|
||||
*/
|
||||
public function __construct(MediaSourceManager $source_manager, EntityFieldManagerInterface $entity_field_manager) {
|
||||
public function __construct(PluginManagerInterface $source_manager, EntityFieldManagerInterface $entity_field_manager) {
|
||||
$this->sourceManager = $source_manager;
|
||||
$this->entityFieldManager = $entity_field_manager;
|
||||
}
|
||||
@@ -118,7 +119,7 @@ class MediaTypeForm extends EntityForm {
|
||||
'#attributes' => ['id' => 'source-dependent'],
|
||||
];
|
||||
|
||||
if ($source) {
|
||||
if (!$this->entity->isNew()) {
|
||||
$source_description = $this->t('<em>The media source cannot be changed after the media type is created.</em>');
|
||||
}
|
||||
else {
|
||||
@@ -131,23 +132,12 @@ class MediaTypeForm extends EntityForm {
|
||||
'#options' => $options,
|
||||
'#description' => $source_description,
|
||||
'#ajax' => ['callback' => '::ajaxHandlerData'],
|
||||
// Rebuilding the form as part of the AJAX request is a workaround to
|
||||
// enforce machine_name validation.
|
||||
// @todo This was added as part of #2932226 and it should be removed once
|
||||
// https://www.drupal.org/project/drupal/issues/2557299 solves it in a
|
||||
// more generic way.
|
||||
'#executes_submit_callback' => TRUE,
|
||||
'#submit' => [[static::class, 'rebuildSubmit']],
|
||||
'#required' => TRUE,
|
||||
// Once the media type is created, its source plugin cannot be changed
|
||||
// anymore.
|
||||
'#disabled' => !empty($source),
|
||||
'#disabled' => !$this->entity->isNew(),
|
||||
];
|
||||
|
||||
if (!$source) {
|
||||
$form['type']['#empty_option'] = $this->t('- Select media source -');
|
||||
}
|
||||
|
||||
if ($source) {
|
||||
// Media source plugin configuration.
|
||||
$form['source_dependent']['source_configuration'] = [
|
||||
@@ -240,18 +230,6 @@ class MediaTypeForm extends EntityForm {
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form submission handler to rebuild the form on select submit.
|
||||
*
|
||||
* @param array $form
|
||||
* Full form array.
|
||||
* @param \Drupal\Core\Form\FormStateInterface $form_state
|
||||
* Current form state.
|
||||
*/
|
||||
public static function rebuildSubmit(array &$form, FormStateInterface $form_state) {
|
||||
$form_state->setRebuild();
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares workflow options to be used in the 'checkboxes' form element.
|
||||
*
|
||||
@@ -373,10 +351,10 @@ class MediaTypeForm extends EntityForm {
|
||||
|
||||
$t_args = ['%name' => $media_type->label()];
|
||||
if ($status === SAVED_UPDATED) {
|
||||
drupal_set_message($this->t('The media type %name has been updated.', $t_args));
|
||||
$this->messenger()->addStatus($this->t('The media type %name has been updated.', $t_args));
|
||||
}
|
||||
elseif ($status === SAVED_NEW) {
|
||||
drupal_set_message($this->t('The media type %name has been added.', $t_args));
|
||||
$this->messenger()->addStatus($this->t('The media type %name has been added.', $t_args));
|
||||
$this->logger('media')->notice('Added media type %name.', $t_args);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,10 @@ interface MediaTypeInterface extends ConfigEntityInterface, EntityDescriptionInt
|
||||
/**
|
||||
* Returns whether thumbnail downloads are queued.
|
||||
*
|
||||
* When using remote media sources, the thumbnail generation could be a slow
|
||||
* process. Using a queue allows for this process to be handled in the
|
||||
* background.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if thumbnails are queued for download later, FALSE if they should be
|
||||
* downloaded now.
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
|
||||
/**
|
||||
* Value object for oEmbed provider endpoints.
|
||||
*
|
||||
* @internal
|
||||
* This class is an internal part of the oEmbed system and should only be
|
||||
* instantiated by instances of Drupal\media\OEmbed\Provider.
|
||||
*/
|
||||
class Endpoint {
|
||||
|
||||
/**
|
||||
* The endpoint's URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* The provider this endpoint belongs to.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\Provider
|
||||
*/
|
||||
protected $provider;
|
||||
|
||||
/**
|
||||
* List of URL schemes supported by the provider.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $schemes;
|
||||
|
||||
/**
|
||||
* List of supported formats. Only 'json' and 'xml' are allowed.
|
||||
*
|
||||
* @var string[]
|
||||
*
|
||||
* @see https://oembed.com/#section2
|
||||
*/
|
||||
protected $formats;
|
||||
|
||||
/**
|
||||
* Whether the provider supports oEmbed discovery.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $supportsDiscovery;
|
||||
|
||||
/**
|
||||
* Endpoint constructor.
|
||||
*
|
||||
* @param string $url
|
||||
* The endpoint URL. May contain a @code '{format}' @endcode placeholder.
|
||||
* @param \Drupal\media\OEmbed\Provider $provider
|
||||
* The provider this endpoint belongs to.
|
||||
* @param string[] $schemes
|
||||
* List of URL schemes supported by the provider.
|
||||
* @param string[] $formats
|
||||
* List of supported formats. Can be "json", "xml" or both.
|
||||
* @param bool $supports_discovery
|
||||
* Whether the provider supports oEmbed discovery.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* If the endpoint URL is empty.
|
||||
*/
|
||||
public function __construct($url, Provider $provider, array $schemes = [], array $formats = [], $supports_discovery = FALSE) {
|
||||
$this->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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
|
||||
/**
|
||||
* Value object for oEmbed providers.
|
||||
*/
|
||||
class Provider {
|
||||
|
||||
/**
|
||||
* The provider name.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $name;
|
||||
|
||||
/**
|
||||
* The provider URL.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* The provider endpoints.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\Endpoint[]
|
||||
*/
|
||||
protected $endpoints = [];
|
||||
|
||||
/**
|
||||
* Provider constructor.
|
||||
*
|
||||
* @param string $name
|
||||
* The provider name.
|
||||
* @param string $url
|
||||
* The provider URL.
|
||||
* @param array[] $endpoints
|
||||
* List of endpoints this provider exposes.
|
||||
*
|
||||
* @throws \Drupal\media\OEmbed\ProviderException
|
||||
*/
|
||||
public function __construct($name, $url, array $endpoints) {
|
||||
if (!UrlHelper::isValid($url, TRUE) || !UrlHelper::isExternal($url)) {
|
||||
throw new ProviderException('Provider @name does not define a valid external URL.', $this);
|
||||
}
|
||||
|
||||
$this->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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
/**
|
||||
* Exception thrown if an oEmbed provider causes an error.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class ProviderException extends \Exception {
|
||||
|
||||
/**
|
||||
* Information about the oEmbed provider which caused the exception.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\Provider
|
||||
*
|
||||
* @see \Drupal\media\OEmbed\ProviderRepositoryInterface::get()
|
||||
*/
|
||||
protected $provider;
|
||||
|
||||
/**
|
||||
* ProviderException constructor.
|
||||
*
|
||||
* @param string $message
|
||||
* The exception message. '@name' will be replaced with the provider name
|
||||
* if available, or '<unknown>' 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() : '<unknown>', $message);
|
||||
parent::__construct($message, 0, $previous);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Component\Datetime\TimeInterface;
|
||||
use Drupal\Component\Serialization\Json;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Cache\UseCacheBackendTrait;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
/**
|
||||
* Retrieves and caches information about oEmbed providers.
|
||||
*/
|
||||
class ProviderRepository implements ProviderRepositoryInterface {
|
||||
|
||||
use UseCacheBackendTrait;
|
||||
|
||||
/**
|
||||
* How long the provider data should be cached, in seconds.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $maxAge;
|
||||
|
||||
/**
|
||||
* The HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\Client
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* URL of a JSON document which contains a database of oEmbed providers.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $providersUrl;
|
||||
|
||||
/**
|
||||
* The time service.
|
||||
*
|
||||
* @var \Drupal\Component\Datetime\TimeInterface
|
||||
*/
|
||||
protected $time;
|
||||
|
||||
/**
|
||||
* Constructs a ProviderRepository instance.
|
||||
*
|
||||
* @param \GuzzleHttp\ClientInterface $http_client
|
||||
* The HTTP client.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory service.
|
||||
* @param \Drupal\Component\Datetime\TimeInterface $time
|
||||
* The time service.
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
|
||||
* (optional) The cache backend.
|
||||
* @param int $max_age
|
||||
* (optional) How long the cache data should be kept. Defaults to a week.
|
||||
*/
|
||||
public function __construct(ClientInterface $http_client, ConfigFactoryInterface $config_factory, TimeInterface $time, CacheBackendInterface $cache_backend = NULL, $max_age = 604800) {
|
||||
$this->httpClient = $http_client;
|
||||
$this->providersUrl = $config_factory->get('media.settings')->get('oembed_providers_url');
|
||||
$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];
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
/**
|
||||
* Defines an interface for a collection of oEmbed provider information.
|
||||
*
|
||||
* The provider repository is responsible for fetching information about all
|
||||
* available oEmbed providers, most likely pulled from the online database at
|
||||
* https://oembed.com/providers.json, and creating \Drupal\media\OEmbed\Provider
|
||||
* value objects for each provider.
|
||||
*/
|
||||
interface ProviderRepositoryInterface {
|
||||
|
||||
/**
|
||||
* Returns information on all available oEmbed providers.
|
||||
*
|
||||
* @return \Drupal\media\OEmbed\Provider[]
|
||||
* Returns an array of provider value objects, keyed by provider name.
|
||||
*
|
||||
* @throws \Drupal\media\OEmbed\ProviderException
|
||||
* If the oEmbed provider information cannot be retrieved.
|
||||
*/
|
||||
public function getAll();
|
||||
|
||||
/**
|
||||
* Returns information for a specific oEmbed provider.
|
||||
*
|
||||
* @param string $provider_name
|
||||
* The name of the provider.
|
||||
*
|
||||
* @return \Drupal\media\OEmbed\Provider
|
||||
* A value object containing information about the provider.
|
||||
*
|
||||
* @throws \InvalidArgumentException
|
||||
* If there is no known oEmbed provider with the specified name.
|
||||
*/
|
||||
public function get($provider_name);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,534 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\Core\Cache\CacheableDependencyInterface;
|
||||
use Drupal\Core\Cache\CacheableDependencyTrait;
|
||||
use Drupal\Core\Url;
|
||||
|
||||
/**
|
||||
* Value object representing an oEmbed resource.
|
||||
*
|
||||
* Data received from an oEmbed provider could be insecure. For example,
|
||||
* resources of the 'rich' type provide an HTML representation which is not
|
||||
* sanitized by this object in any way. Any values you retrieve from this object
|
||||
* should be treated as potentially dangerous user input and carefully validated
|
||||
* and sanitized before being displayed or otherwise manipulated by your code.
|
||||
*
|
||||
* Valid resource types are defined in the oEmbed specification and represented
|
||||
* by the TYPE_* constants in this class.
|
||||
*
|
||||
* @see https://oembed.com/#section2
|
||||
*
|
||||
* @internal
|
||||
* This class is an internal part of the oEmbed system and should only be
|
||||
* instantiated by
|
||||
* \Drupal\media\OEmbed\ResourceFetcherInterface::fetchResource().
|
||||
*/
|
||||
class Resource implements CacheableDependencyInterface {
|
||||
|
||||
use CacheableDependencyTrait;
|
||||
|
||||
/**
|
||||
* The resource type for link resources.
|
||||
*/
|
||||
const TYPE_LINK = 'link';
|
||||
|
||||
/**
|
||||
* The resource type for photo resources.
|
||||
*/
|
||||
const TYPE_PHOTO = 'photo';
|
||||
|
||||
/**
|
||||
* The resource type for rich resources.
|
||||
*/
|
||||
const TYPE_RICH = 'rich';
|
||||
|
||||
/**
|
||||
* The resource type for video resources.
|
||||
*/
|
||||
const TYPE_VIDEO = 'video';
|
||||
|
||||
/**
|
||||
* The resource type. Can be one of the static::TYPE_* constants.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $type;
|
||||
|
||||
/**
|
||||
* The resource provider.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\Provider
|
||||
*/
|
||||
protected $provider;
|
||||
|
||||
/**
|
||||
* A text title, describing the resource.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $title;
|
||||
|
||||
/**
|
||||
* The name of the author/owner of the resource.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $authorName;
|
||||
|
||||
/**
|
||||
* A URL for the author/owner of the resource.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $authorUrl;
|
||||
|
||||
/**
|
||||
* A URL to a thumbnail image representing the resource.
|
||||
*
|
||||
* The thumbnail must respect any maxwidth and maxheight parameters passed
|
||||
* to the oEmbed endpoint. If this parameter is present, thumbnail_width and
|
||||
* thumbnail_height must also be present.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @see \Drupal\media\OEmbed\UrlResolverInterface::getResourceUrl()
|
||||
* @see https://oembed.com/#section2
|
||||
*/
|
||||
protected $thumbnailUrl;
|
||||
|
||||
/**
|
||||
* The width of the thumbnail, in pixels.
|
||||
*
|
||||
* If this parameter is present, thumbnail_url and thumbnail_height must also
|
||||
* be present.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $thumbnailWidth;
|
||||
|
||||
/**
|
||||
* The height of the thumbnail, in pixels.
|
||||
*
|
||||
* If this parameter is present, thumbnail_url and thumbnail_width must also
|
||||
* be present.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $thumbnailHeight;
|
||||
|
||||
/**
|
||||
* The width of the resource, in pixels.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $width;
|
||||
|
||||
/**
|
||||
* The height of the resource, in pixels.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $height;
|
||||
|
||||
/**
|
||||
* The resource URL. Only applies to 'photo' and 'link' resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* The HTML representation of the resource.
|
||||
*
|
||||
* Only applies to 'rich' and 'video' resources.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $html;
|
||||
|
||||
/**
|
||||
* Resource constructor.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
protected function __construct(Provider $provider = NULL, $title = NULL, $author_name = NULL, $author_url = NULL, $cache_age = NULL, $thumbnail_url = NULL, $thumbnail_width = NULL, $thumbnail_height = NULL) {
|
||||
$this->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.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
/**
|
||||
* Exception thrown if an oEmbed resource cannot be fetched or parsed.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class ResourceException extends \Exception {
|
||||
|
||||
/**
|
||||
* The URL of the resource.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $url;
|
||||
|
||||
/**
|
||||
* The resource data.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $data = [];
|
||||
|
||||
/**
|
||||
* ResourceException constructor.
|
||||
*
|
||||
* @param string $message
|
||||
* The exception message.
|
||||
* @param string $url
|
||||
* The URL of the resource. Can be the actual endpoint URL or the canonical
|
||||
* URL.
|
||||
* @param array $data
|
||||
* (optional) The raw resource data, if available.
|
||||
* @param \Exception $previous
|
||||
* (optional) The previous exception, if any.
|
||||
*/
|
||||
public function __construct($message, $url, array $data = [], \Exception $previous = NULL) {
|
||||
$this->url = $url;
|
||||
$this->data = $data;
|
||||
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 getData() {
|
||||
return $this->data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Component\Serialization\Json;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Cache\UseCacheBackendTrait;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use Symfony\Component\Serializer\Encoder\XmlEncoder;
|
||||
|
||||
/**
|
||||
* Fetches and caches oEmbed resources.
|
||||
*/
|
||||
class ResourceFetcher implements ResourceFetcherInterface {
|
||||
|
||||
use UseCacheBackendTrait;
|
||||
|
||||
/**
|
||||
* The HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\Client
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* The oEmbed provider repository service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ProviderRepositoryInterface
|
||||
*/
|
||||
protected $providers;
|
||||
|
||||
/**
|
||||
* Constructs a ResourceFetcher object.
|
||||
*
|
||||
* @param \GuzzleHttp\ClientInterface $http_client
|
||||
* The HTTP client.
|
||||
* @param \Drupal\media\OEmbed\ProviderRepositoryInterface $providers
|
||||
* The oEmbed provider repository service.
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
|
||||
* (optional) The cache backend.
|
||||
*/
|
||||
public function __construct(ClientInterface $http_client, ProviderRepositoryInterface $providers, CacheBackendInterface $cache_backend = NULL) {
|
||||
$this->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 ResourceException('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 ResourceException('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\ResourceException
|
||||
* 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 ResourceException("Resource version must be '1.0'", $url, $data);
|
||||
}
|
||||
|
||||
// Prepare the arguments to pass to the factory method.
|
||||
$provider = $data['provider_name'] ? $this->providers->get($data['provider_name']) : NULL;
|
||||
|
||||
// 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 {
|
||||
switch ($data['type']) {
|
||||
case Resource::TYPE_LINK:
|
||||
return Resource::link(
|
||||
$data['url'],
|
||||
$provider,
|
||||
$data['title'],
|
||||
$data['author_name'],
|
||||
$data['author_url'],
|
||||
$data['cache_age'],
|
||||
$data['thumbnail_url'],
|
||||
$data['thumbnail_width'],
|
||||
$data['thumbnail_height']
|
||||
);
|
||||
|
||||
case Resource::TYPE_PHOTO:
|
||||
return Resource::photo(
|
||||
$data['url'],
|
||||
$data['width'],
|
||||
$data['height'],
|
||||
$provider,
|
||||
$data['title'],
|
||||
$data['author_name'],
|
||||
$data['author_url'],
|
||||
$data['cache_age'],
|
||||
$data['thumbnail_url'],
|
||||
$data['thumbnail_width'],
|
||||
$data['thumbnail_height']
|
||||
);
|
||||
|
||||
case Resource::TYPE_RICH:
|
||||
return Resource::rich(
|
||||
$data['html'],
|
||||
$data['width'],
|
||||
$data['height'],
|
||||
$provider,
|
||||
$data['title'],
|
||||
$data['author_name'],
|
||||
$data['author_url'],
|
||||
$data['cache_age'],
|
||||
$data['thumbnail_url'],
|
||||
$data['thumbnail_width'],
|
||||
$data['thumbnail_height']
|
||||
);
|
||||
case Resource::TYPE_VIDEO:
|
||||
return Resource::video(
|
||||
$data['html'],
|
||||
$data['width'],
|
||||
$data['height'],
|
||||
$provider,
|
||||
$data['title'],
|
||||
$data['author_name'],
|
||||
$data['author_url'],
|
||||
$data['cache_age'],
|
||||
$data['thumbnail_url'],
|
||||
$data['thumbnail_width'],
|
||||
$data['thumbnail_height']
|
||||
);
|
||||
|
||||
default:
|
||||
throw new ResourceException('Unknown resource type: ' . $data['type'], $url, $data);
|
||||
}
|
||||
}
|
||||
catch (\InvalidArgumentException $e) {
|
||||
throw new ResourceException($e->getMessage(), $url, $data, $e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
/**
|
||||
* Defines an interface for an oEmbed resource fetcher service.
|
||||
*
|
||||
* The resource fetcher's only responsibility is to retrieve oEmbed resource
|
||||
* data from an endpoint URL (i.e., as returned by
|
||||
* \Drupal\media\OEmbed\UrlResolverInterface::getResourceUrl()) and return a
|
||||
* \Drupal\media\OEmbed\Resource value object.
|
||||
*/
|
||||
interface ResourceFetcherInterface {
|
||||
|
||||
/**
|
||||
* Fetches an oEmbed resource.
|
||||
*
|
||||
* @param string $url
|
||||
* Endpoint-specific URL of the oEmbed resource.
|
||||
*
|
||||
* @return \Drupal\media\OEmbed\Resource
|
||||
* A resource object built from the oEmbed resource data.
|
||||
*
|
||||
* @see https://oembed.com/#section2
|
||||
*
|
||||
* @throws \Drupal\media\OEmbed\ResourceException
|
||||
* If the oEmbed endpoint is not reachable or the response returns an
|
||||
* unexpected Content-Type header.
|
||||
*/
|
||||
public function fetchResource($url);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\Cache\UseCacheBackendTrait;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
|
||||
/**
|
||||
* Converts oEmbed media URLs into endpoint-specific resource URLs.
|
||||
*/
|
||||
class UrlResolver implements UrlResolverInterface {
|
||||
|
||||
use UseCacheBackendTrait;
|
||||
|
||||
/**
|
||||
* The HTTP client.
|
||||
*
|
||||
* @var \GuzzleHttp\Client
|
||||
*/
|
||||
protected $httpClient;
|
||||
|
||||
/**
|
||||
* The OEmbed provider repository service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ProviderRepositoryInterface
|
||||
*/
|
||||
protected $providers;
|
||||
|
||||
/**
|
||||
* The OEmbed resource fetcher service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ResourceFetcherInterface
|
||||
*/
|
||||
protected $resourceFetcher;
|
||||
|
||||
/**
|
||||
* The module handler service.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Static cache of discovered oEmbed resource URLs, keyed by canonical URL.
|
||||
*
|
||||
* A discovered resource URL is the actual endpoint URL for a specific media
|
||||
* object, fetched from its canonical URL.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $urlCache = [];
|
||||
|
||||
/**
|
||||
* Constructs a UrlResolver object.
|
||||
*
|
||||
* @param \Drupal\media\OEmbed\ProviderRepositoryInterface $providers
|
||||
* The oEmbed provider repository service.
|
||||
* @param \Drupal\media\OEmbed\ResourceFetcherInterface $resource_fetcher
|
||||
* The OEmbed resource fetcher service.
|
||||
* @param \GuzzleHttp\ClientInterface $http_client
|
||||
* The HTTP client.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler service.
|
||||
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
|
||||
* (optional) The cache backend.
|
||||
*/
|
||||
public function __construct(ProviderRepositoryInterface $providers, ResourceFetcherInterface $resource_fetcher, ClientInterface $http_client, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend = NULL) {
|
||||
$this->providers = $providers;
|
||||
$this->resourceFetcher = $resource_fetcher;
|
||||
$this->httpClient = $http_client;
|
||||
$this->moduleHandler = $module_handler;
|
||||
$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\ResourceException
|
||||
* If the resource cannot be retrieved.
|
||||
*/
|
||||
protected function discoverResourceUrl($url) {
|
||||
try {
|
||||
$response = $this->httpClient->get($url);
|
||||
}
|
||||
catch (RequestException $e) {
|
||||
throw new ResourceException('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 ResourceException('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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\OEmbed;
|
||||
|
||||
/**
|
||||
* Defines the interface for the oEmbed URL resolver service.
|
||||
*
|
||||
* The URL resolver is responsible for converting oEmbed-compatible media asset
|
||||
* URLs into canonical resource URLs, at which an oEmbed representation of the
|
||||
* asset can be retrieved.
|
||||
*/
|
||||
interface UrlResolverInterface {
|
||||
|
||||
/**
|
||||
* Tries to determine the oEmbed provider for a media asset URL.
|
||||
*
|
||||
* @param string $url
|
||||
* The media asset URL.
|
||||
*
|
||||
* @return \Drupal\media\OEmbed\Provider
|
||||
* The oEmbed provider for the asset.
|
||||
*
|
||||
* @throws \Drupal\media\OEmbed\ResourceException
|
||||
* If the provider cannot be determined.
|
||||
* @throws \Drupal\media\OEmbed\ProviderException
|
||||
* If tne oEmbed provider causes an error.
|
||||
*/
|
||||
public function getProviderByUrl($url);
|
||||
|
||||
/**
|
||||
* Builds the resource URL for a media asset URL.
|
||||
*
|
||||
* @param string $url
|
||||
* The media asset URL.
|
||||
* @param int $max_width
|
||||
* (optional) Maximum width of the oEmbed resource, in pixels.
|
||||
* @param int $max_height
|
||||
* (optional) Maximum height of the oEmbed resource, in pixels.
|
||||
*
|
||||
* @return string
|
||||
* Returns the resource URL corresponding to the given media item URL.
|
||||
*/
|
||||
public function getResourceUrl($url, $max_width = NULL, $max_height = NULL);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\Field\FieldFormatter;
|
||||
|
||||
use Drupal\Core\Cache\CacheableMetadata;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Field\FieldDefinitionInterface;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Field\FormatterBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
|
||||
use Drupal\Core\Messenger\MessengerInterface;
|
||||
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\media\Entity\MediaType;
|
||||
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 Drupal\media\Plugin\media\Source\OEmbedInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Plugin implementation of the 'oembed' formatter.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*
|
||||
* @FieldFormatter(
|
||||
* id = "oembed",
|
||||
* label = @Translation("oEmbed content"),
|
||||
* field_types = {
|
||||
* "link",
|
||||
* "string",
|
||||
* "string_long",
|
||||
* },
|
||||
* )
|
||||
*/
|
||||
class OEmbedFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
|
||||
|
||||
/**
|
||||
* The messenger service.
|
||||
*
|
||||
* @var \Drupal\Core\Messenger\MessengerInterface
|
||||
*/
|
||||
protected $messenger;
|
||||
|
||||
/**
|
||||
* The oEmbed resource fetcher.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ResourceFetcherInterface
|
||||
*/
|
||||
protected $resourceFetcher;
|
||||
|
||||
/**
|
||||
* The oEmbed URL resolver service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\UrlResolverInterface
|
||||
*/
|
||||
protected $urlResolver;
|
||||
|
||||
/**
|
||||
* The logger service.
|
||||
*
|
||||
* @var \Drupal\Core\Logger\LoggerChannelInterface
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* The media settings config.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ImmutableConfig
|
||||
*/
|
||||
protected $config;
|
||||
|
||||
/**
|
||||
* The iFrame URL helper service.
|
||||
*
|
||||
* @var \Drupal\media\IFrameUrlHelper
|
||||
*/
|
||||
protected $iFrameUrlHelper;
|
||||
|
||||
/**
|
||||
* Constructs an OEmbedFormatter instance.
|
||||
*
|
||||
* @param string $plugin_id
|
||||
* The plugin ID for the formatter.
|
||||
* @param mixed $plugin_definition
|
||||
* The plugin implementation definition.
|
||||
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
|
||||
* The definition of the field to which the formatter is associated.
|
||||
* @param array $settings
|
||||
* The formatter settings.
|
||||
* @param string $label
|
||||
* The formatter label display setting.
|
||||
* @param string $view_mode
|
||||
* The view mode.
|
||||
* @param array $third_party_settings
|
||||
* Any third party settings.
|
||||
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
|
||||
* The messenger 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\Core\Logger\LoggerChannelFactoryInterface $logger_factory
|
||||
* The logger factory service.
|
||||
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
|
||||
* The config factory service.
|
||||
* @param \Drupal\media\IFrameUrlHelper $iframe_url_helper
|
||||
* The iFrame URL helper service.
|
||||
*/
|
||||
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, MessengerInterface $messenger, ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver, LoggerChannelFactoryInterface $logger_factory, ConfigFactoryInterface $config_factory, IFrameUrlHelper $iframe_url_helper) {
|
||||
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
|
||||
$this->messenger = $messenger;
|
||||
$this->resourceFetcher = $resource_fetcher;
|
||||
$this->urlResolver = $url_resolver;
|
||||
$this->logger = $logger_factory->get('media');
|
||||
$this->config = $config_factory->get('media.settings');
|
||||
$this->iFrameUrlHelper = $iframe_url_helper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'),
|
||||
$container->get('media.oembed.iframe_url_helper')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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', [], [
|
||||
'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
|
||||
$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) {
|
||||
if ($field_definition->getTargetEntityTypeId() !== 'media') {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
if (parent::isApplicable($field_definition)) {
|
||||
$media_type = $field_definition->getTargetBundle();
|
||||
|
||||
if ($media_type) {
|
||||
$media_type = MediaType::load($media_type);
|
||||
return $media_type && $media_type->getSource() instanceof OEmbedInterface;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\Field\FieldWidget;
|
||||
|
||||
use Drupal\Core\Field\FieldDefinitionInterface;
|
||||
use Drupal\Core\Field\FieldItemListInterface;
|
||||
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextfieldWidget;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\media\Entity\MediaType;
|
||||
use Drupal\media\Plugin\media\Source\OEmbedInterface;
|
||||
|
||||
/**
|
||||
* Plugin implementation of the 'oembed_textfield' widget.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*
|
||||
* @FieldWidget(
|
||||
* id = "oembed_textfield",
|
||||
* label = @Translation("oEmbed URL"),
|
||||
* field_types = {
|
||||
* "string",
|
||||
* },
|
||||
* )
|
||||
*/
|
||||
class OEmbedWidget extends StringTextfieldWidget {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
|
||||
$element = parent::formElement($items, $delta, $element, $form, $form_state);
|
||||
|
||||
/** @var \Drupal\media\Plugin\media\Source\OEmbedInterface $source */
|
||||
$source = $items->getEntity()->getSource();
|
||||
$message = $this->t('You can link to media from the following services: @providers', ['@providers' => implode(', ', $source->getProviders())]);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\Validation\Constraint;
|
||||
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
|
||||
/**
|
||||
* Checks if a value represents a valid oEmbed resource URL.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*
|
||||
* @Constraint(
|
||||
* id = "oembed_resource",
|
||||
* label = @Translation("oEmbed resource", context = "Validation"),
|
||||
* type = {"link", "string", "string_long"}
|
||||
* )
|
||||
*/
|
||||
class OEmbedResourceConstraint extends Constraint {
|
||||
|
||||
/**
|
||||
* The error message if the URL does not match any known provider.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $unknownProviderMessage = 'The given URL does not match any known oEmbed providers.';
|
||||
|
||||
/**
|
||||
* The error message if the URL matches a disallowed provider.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $disallowedProviderMessage = 'Sorry, the @name provider is not allowed.';
|
||||
|
||||
/**
|
||||
* The error message if the URL is not a valid oEmbed resource.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $invalidResourceMessage = 'The provided URL does not represent a valid oEmbed resource.';
|
||||
|
||||
/**
|
||||
* The error message if an unexpected behavior occurs.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $providerErrorMessage = 'An error occurred while trying to retrieve the oEmbed provider database.';
|
||||
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\Validation\Constraint;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
|
||||
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
|
||||
use Drupal\media\OEmbed\ProviderException;
|
||||
use Drupal\media\OEmbed\ResourceException;
|
||||
use Drupal\media\OEmbed\ResourceFetcherInterface;
|
||||
use Drupal\media\OEmbed\UrlResolverInterface;
|
||||
use Drupal\media\Plugin\media\Source\OEmbedInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\Validator\Constraint;
|
||||
use Symfony\Component\Validator\ConstraintValidator;
|
||||
|
||||
/**
|
||||
* Validates oEmbed resource URLs.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class OEmbedResourceConstraintValidator extends ConstraintValidator implements ContainerInjectionInterface {
|
||||
|
||||
/**
|
||||
* The oEmbed URL resolver service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\UrlResolverInterface
|
||||
*/
|
||||
protected $urlResolver;
|
||||
|
||||
/**
|
||||
* The resource fetcher service.
|
||||
*
|
||||
* @var \Drupal\media\OEmbed\ResourceFetcherInterface
|
||||
*/
|
||||
protected $resourceFetcher;
|
||||
|
||||
/**
|
||||
* The logger service.
|
||||
*
|
||||
* @var \Drupal\Core\Logger\LoggerChannelInterface
|
||||
*/
|
||||
protected $logger;
|
||||
|
||||
/**
|
||||
* Constructs a new OEmbedResourceConstraintValidator.
|
||||
*
|
||||
* @param \Drupal\media\OEmbed\UrlResolverInterface $url_resolver
|
||||
* The oEmbed URL resolver service.
|
||||
* @param \Drupal\media\OEmbed\ResourceFetcherInterface $resource_fetcher
|
||||
* The resource fetcher service.
|
||||
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
|
||||
* The logger service.
|
||||
*/
|
||||
public function __construct(UrlResolverInterface $url_resolver, ResourceFetcherInterface $resource_fetcher, LoggerChannelFactoryInterface $logger_factory) {
|
||||
$this->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->getProviders(), 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);
|
||||
}
|
||||
|
||||
// The oEmbed system makes heavy use of exception wrapping, so log the
|
||||
// entire exception chain to help with troubleshooting.
|
||||
do {
|
||||
// @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());
|
||||
$e = $e->getPrevious();
|
||||
} while ($e);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,6 +22,13 @@ use Drupal\media\MediaSourceBase;
|
||||
*/
|
||||
class File extends MediaSourceBase {
|
||||
|
||||
/**
|
||||
* Key for "Name" metadata attribute.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const METADATA_ATTRIBUTE_NAME = 'name';
|
||||
|
||||
/**
|
||||
* Key for "MIME type" metadata attribute.
|
||||
*
|
||||
@@ -36,12 +43,12 @@ class File extends MediaSourceBase {
|
||||
*/
|
||||
const METADATA_ATTRIBUTE_SIZE = 'filesize';
|
||||
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getMetadataAttributes() {
|
||||
return [
|
||||
static::METADATA_ATTRIBUTE_NAME => $this->t('Name'),
|
||||
static::METADATA_ATTRIBUTE_MIME => $this->t('MIME type'),
|
||||
static::METADATA_ATTRIBUTE_SIZE => $this->t('File size'),
|
||||
];
|
||||
@@ -58,15 +65,16 @@ class File extends MediaSourceBase {
|
||||
return parent::getMetadata($media, $attribute_name);
|
||||
}
|
||||
switch ($attribute_name) {
|
||||
case 'mimetype':
|
||||
return $file->getMimeType();
|
||||
|
||||
case 'filesize':
|
||||
return $file->getSize();
|
||||
|
||||
case static::METADATA_ATTRIBUTE_NAME:
|
||||
case 'default_name':
|
||||
return $file->getFilename();
|
||||
|
||||
case static::METADATA_ATTRIBUTE_MIME:
|
||||
return $file->getMimeType();
|
||||
|
||||
case static::METADATA_ATTRIBUTE_SIZE:
|
||||
return $file->getSize();
|
||||
|
||||
case 'thumbnail_uri':
|
||||
return $this->getThumbnail($file) ?: parent::getMetadata($media, $attribute_name);
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Entity\EntityFieldManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Field\FieldTypePluginManagerInterface;
|
||||
use Drupal\Core\File\FileSystem;
|
||||
use Drupal\Core\File\FileSystemInterface;
|
||||
use Drupal\Core\Image\ImageFactory;
|
||||
use Drupal\media\MediaInterface;
|
||||
use Drupal\media\MediaTypeInterface;
|
||||
@@ -51,7 +51,7 @@ class Image extends File {
|
||||
/**
|
||||
* The file system service.
|
||||
*
|
||||
* @var \Drupal\Core\File\FileSystem
|
||||
* @var \Drupal\Core\File\FileSystemInterface
|
||||
*/
|
||||
protected $fileSystem;
|
||||
|
||||
@@ -74,10 +74,10 @@ class Image extends File {
|
||||
* The config factory service.
|
||||
* @param \Drupal\Core\Image\ImageFactory $image_factory
|
||||
* The image factory.
|
||||
* @param \Drupal\Core\File\FileSystem $file_system
|
||||
* @param \Drupal\Core\File\FileSystemInterface $file_system
|
||||
* The file system service.
|
||||
*/
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, ConfigFactoryInterface $config_factory, ImageFactory $image_factory, FileSystem $file_system) {
|
||||
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, ConfigFactoryInterface $config_factory, ImageFactory $image_factory, FileSystemInterface $file_system) {
|
||||
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
|
||||
|
||||
$this->imageFactory = $image_factory;
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\media\Source;
|
||||
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
|
||||
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
|
||||
use Drupal\Core\Entity\EntityFieldManagerInterface;
|
||||
use Drupal\Core\Entity\EntityTypeManagerInterface;
|
||||
use Drupal\Core\Field\FieldTypePluginManagerInterface;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Logger\LoggerChannelInterface;
|
||||
use Drupal\Core\Messenger\MessengerInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\media\IFrameUrlHelper;
|
||||
use Drupal\media\OEmbed\Resource;
|
||||
use Drupal\media\OEmbed\ResourceException;
|
||||
use Drupal\media\MediaSourceBase;
|
||||
use Drupal\media\MediaInterface;
|
||||
use Drupal\media\MediaTypeInterface;
|
||||
use Drupal\media\OEmbed\ResourceFetcherInterface;
|
||||
use Drupal\media\OEmbed\UrlResolverInterface;
|
||||
use GuzzleHttp\ClientInterface;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Provides a media source plugin for oEmbed resources.
|
||||
*
|
||||
* For security reasons, the oEmbed source (and, therefore, anything that
|
||||
* extends it) obeys a hard-coded list of allowed third-party oEmbed providers
|
||||
* set in its plugin definition's providers array. This array is a set of
|
||||
* provider names, exactly as they appear in the canonical oEmbed provider
|
||||
* database at https://oembed.com/providers.json.
|
||||
*
|
||||
* You can implement support for additional providers by defining a new plugin
|
||||
* that uses this class. This can be done in hook_media_source_info_alter().
|
||||
* For example:
|
||||
* @code
|
||||
* <?php
|
||||
*
|
||||
* function example_media_source_info_alter(array &$sources) {
|
||||
* $sources['artwork'] = [
|
||||
* 'id' => 'artwork',
|
||||
* 'label' => t('Artwork'),
|
||||
* 'description' => t('Use artwork from Flickr and DeviantArt.'),
|
||||
* 'allowed_field_types' => ['string'],
|
||||
* 'default_thumbnail_filename' => 'no-thumbnail.png',
|
||||
* '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",
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* The iFrame URL helper service.
|
||||
*
|
||||
* @var \Drupal\media\IFrameUrlHelper
|
||||
*/
|
||||
protected $iFrameUrlHelper;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param \Drupal\media\IFrameUrlHelper $iframe_url_helper
|
||||
* The iFrame URL helper 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, IFrameUrlHelper $iframe_url_helper) {
|
||||
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;
|
||||
$this->iFrameUrlHelper = $iframe_url_helper;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'),
|
||||
$container->get('media.oembed.iframe_url_helper')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'),
|
||||
'default_name' => $this->t('Default name of the media item'),
|
||||
'thumbnail_uri' => $this->t('Local URI 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 '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->getLocalThumbnailUri($resource) ?: 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_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->iFrameUrlHelper->isSecure($domain)) {
|
||||
array_unshift($form, [
|
||||
'#markup' => '<p>' . $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. <a href=":url" target="_blank">You can specify a different domain for serving oEmbed content here</a> (opens in a new window).', [
|
||||
':url' => Url::fromRoute('media.settings')->setAbsolute()->toString(),
|
||||
]) . '</p>',
|
||||
]);
|
||||
}
|
||||
|
||||
$form['thumbnails_directory'] = [
|
||||
'#type' => 'textfield',
|
||||
'#title' => $this->t('Thumbnails location'),
|
||||
'#default_value' => $this->configuration['thumbnails_directory'],
|
||||
'#description' => $this->t('Thumbnails will be fetched from the provider for local usage. This is the URI of the directory where they will be placed.'),
|
||||
'#required' => TRUE,
|
||||
];
|
||||
|
||||
$configuration = $this->getConfiguration();
|
||||
$plugin_definition = $this->getPluginDefinition();
|
||||
|
||||
$form['providers'] = [
|
||||
'#type' => 'checkboxes',
|
||||
'#title' => $this->t('Allowed providers'),
|
||||
'#default_value' => $configuration['providers'],
|
||||
'#options' => array_combine($plugin_definition['providers'], $plugin_definition['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['providers'] = array_filter(array_values($configuration['providers']));
|
||||
$this->setConfiguration($configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
|
||||
$thumbnails_directory = $form_state->getValue('thumbnails_directory');
|
||||
if (!file_valid_uri($thumbnails_directory)) {
|
||||
$form_state->setErrorByName('thumbnails_directory', $this->t('@path is not a valid path.', [
|
||||
'@path' => $thumbnails_directory,
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function defaultConfiguration() {
|
||||
return [
|
||||
'thumbnails_directory' => 'public://oembed_thumbnails',
|
||||
'providers' => [],
|
||||
] + parent::defaultConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the local URI for a resource thumbnail.
|
||||
*
|
||||
* If the thumbnail is not already locally stored, this method will attempt
|
||||
* to download it.
|
||||
*
|
||||
* @param \Drupal\media\OEmbed\Resource $resource
|
||||
* The oEmbed resource.
|
||||
*
|
||||
* @return string|null
|
||||
* The local thumbnail URI, or NULL if it could not be downloaded, or if the
|
||||
* resource has no thumbnail at all.
|
||||
*
|
||||
* @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 getLocalThumbnailUri(Resource $resource) {
|
||||
// If there is no remote thumbnail, there's nothing for us to fetch here.
|
||||
$remote_thumbnail_url = $resource->getThumbnailUrl();
|
||||
if (!$remote_thumbnail_url) {
|
||||
return NULL;
|
||||
}
|
||||
$remote_thumbnail_url = $remote_thumbnail_url->toString();
|
||||
|
||||
// Compute the local thumbnail URI, regardless of whether or not it exists.
|
||||
$configuration = $this->getConfiguration();
|
||||
$directory = $configuration['thumbnails_directory'];
|
||||
$local_thumbnail_uri = "$directory/" . Crypt::hashBase64($remote_thumbnail_url) . '.' . pathinfo($remote_thumbnail_url, PATHINFO_EXTENSION);
|
||||
|
||||
// If the local thumbnail already exists, return its URI.
|
||||
if (file_exists($local_thumbnail_uri)) {
|
||||
return $local_thumbnail_uri;
|
||||
}
|
||||
|
||||
// The local thumbnail doesn't exist yet, so try to download it. First,
|
||||
// ensure that the destination directory is writable, and if it's not,
|
||||
// log an error and bail out.
|
||||
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 NULL;
|
||||
}
|
||||
|
||||
$error_message = 'Could not download remote thumbnail from {url}.';
|
||||
$error_context = [
|
||||
'url' => $remote_thumbnail_url,
|
||||
];
|
||||
try {
|
||||
$response = $this->httpClient->get($remote_thumbnail_url);
|
||||
if ($response->getStatusCode() === 200) {
|
||||
$success = file_unmanaged_save_data((string) $response->getBody(), $local_thumbnail_uri, FILE_EXISTS_REPLACE);
|
||||
|
||||
if ($success) {
|
||||
return $local_thumbnail_uri;
|
||||
}
|
||||
else {
|
||||
$this->logger->warning($error_message, $error_context);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (RequestException $e) {
|
||||
$this->logger->warning($e->getMessage());
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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 getProviders() {
|
||||
$configuration = $this->getConfiguration();
|
||||
return $configuration['providers'] ?: $this->getPluginDefinition()['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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\media\Source;
|
||||
|
||||
use Drupal\Component\Plugin\Derivative\DeriverBase;
|
||||
|
||||
/**
|
||||
* Derives media source plugin definitions for supported oEmbed providers.
|
||||
*
|
||||
* @internal
|
||||
* This is an internal part of the oEmbed system and should only be used by
|
||||
* oEmbed-related code in Drupal core.
|
||||
*/
|
||||
class OEmbedDeriver extends DeriverBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getDerivativeDefinitions($base_plugin_definition) {
|
||||
$this->derivatives = [
|
||||
'video' => [
|
||||
'id' => 'video',
|
||||
'label' => t('Remote video'),
|
||||
'description' => t('Use remote video URL for reusable media.'),
|
||||
'providers' => ['YouTube', 'Vimeo'],
|
||||
'default_thumbnail_filename' => 'video.png',
|
||||
] + $base_plugin_definition,
|
||||
];
|
||||
return parent::getDerivativeDefinitions($base_plugin_definition);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\media\Plugin\media\Source;
|
||||
|
||||
use Drupal\media\MediaSourceFieldConstraintsInterface;
|
||||
|
||||
/**
|
||||
* Defines additional functionality for source plugins that use oEmbed.
|
||||
*/
|
||||
interface OEmbedInterface extends MediaSourceFieldConstraintsInterface {
|
||||
|
||||
/**
|
||||
* Returns the oEmbed provider names.
|
||||
*
|
||||
* The allowed providers can be configured by the user. If it is not
|
||||
* configured, all providers supported by the plugin are returned.
|
||||
*
|
||||
* @return string[]
|
||||
* A list of oEmbed provider names.
|
||||
*/
|
||||
public function getProviders();
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user