You are here

class Facebook in Media entity facebook 3.x

Same name and namespace in other branches
  1. 8.2 src/Plugin/media/Source/Facebook.php \Drupal\media_entity_facebook\Plugin\media\Source\Facebook

Facebook entity media source.

Plugin annotation


@MediaSource(
  id = "facebook",
  label = @Translation("Facebook"),
  description = @Translation("Embed facebook photos and video posts using Facebook's graph API."),
  allowed_field_types = {"string_long"},
  default_thumbnail_filename = "facebook.png",
  forms = {
    "media_library_add" = "\Drupal\media_entity_facebook\Form\FacebookMediaLibraryAddForm",
  }
)

Hierarchy

Expanded class hierarchy of Facebook

2 files declare their use of Facebook
FacebookEmbedCodeConstraintValidator.php in src/Plugin/Validation/Constraint/FacebookEmbedCodeConstraintValidator.php
FacebookEmbedFormatter.php in src/Plugin/Field/FieldFormatter/FacebookEmbedFormatter.php

File

src/Plugin/media/Source/Facebook.php, line 31

Namespace

Drupal\media_entity_facebook\Plugin\media\Source
View source
class Facebook extends MediaSourceBase implements MediaSourceFieldConstraintsInterface {

  /**
   * Facebook Fetcher.
   *
   * @var \Drupal\media_entity_facebook\FacebookFetcher
   */
  protected $facebookFetcher;

  /**
   * Constructs Facebook media source.
   *
   * @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
   *   Entity type manager service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   Entity field manager service.
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
   *   The field type plugin manager service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\media_entity_facebook\FacebookFetcher $facebook_fetcher
   *   The facebook fetcher.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, FieldTypePluginManagerInterface $field_type_manager, ConfigFactoryInterface $config_factory, FacebookFetcher $facebook_fetcher) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
    $this->facebookFetcher = $facebook_fetcher;
  }

  /**
   * {@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('plugin.manager.field.field_type'), $container
      ->get('config.factory'), $container
      ->get('media_entity_facebook.facebook_fetcher'));
  }

  /**
   * {@inheritdoc}
   */
  public function getMetadataAttributes() {
    return [
      'author_name' => $this
        ->t('Author Name'),
      'width' => $this
        ->t('Width'),
      'height' => $this
        ->t('Height'),
      'url' => $this
        ->t('URL'),
      'html' => $this
        ->t('HTML'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getMetadata(MediaInterface $media, $attribute_name) {
    $content_url = $this
      ->getFacebookUrl($media);
    if ($content_url === FALSE) {
      return FALSE;
    }
    $data = $this->facebookFetcher
      ->getOembedData($content_url);
    if ($data === FALSE) {
      return FALSE;
    }
    switch ($attribute_name) {
      case 'author_name':
        return $data['author_name'];
      case 'width':
        return $data['width'];
      case 'height':
        return $data['height'];
      case 'url':
        return $this
          ->getFacebookUrl($media);
      case 'html':
        return $data['html'];
      default:
        return parent::getMetadata($media, $attribute_name);
    }
  }

  /**
   * Runs preg_match on embed code/URL.
   *
   * @param \Drupal\media\MediaInterface $media
   *   Media object.
   *
   * @return string|false
   *   The facebook url or FALSE if there is no field or it contains invalid
   *   data.
   */
  protected function getFacebookUrl(MediaInterface $media) {
    if (isset($this->configuration['source_field'])) {
      $source_field = $this->configuration['source_field'];
      if ($media
        ->hasField($source_field)) {
        $property_name = $media->{$source_field}
          ->first()
          ->mainPropertyName();
        $embed = $media->{$source_field}->{$property_name};
        return static::parseFacebookEmbedField($embed);
      }
    }
    return FALSE;
  }

  /**
   * Extract a Facebook content URL from a string.
   *
   * Typically users will enter an iframe embed code that Facebook provides, so
   * which needs to be parsed to extract the actual post URL.
   *
   * Users may also enter the actual content URL - in which case we just return
   * the value if it matches our expected format.
   *
   * @param string $data
   *   The string that contains the Facebook post URL.
   *
   * @return string|bool
   *   The post URL, or FALSE if one cannot be found.
   */
  public static function parseFacebookEmbedField($data) {
    $data = trim($data);

    // Ideally we would verify that the content URL matches an exact pattern,
    // but Facebook has a ton of different ways posts/notes/videos/etc URLs can
    // be formatted, so it's not practical to try and validate them. Instead,
    // just validate that the content URL is from the facebook domain.
    $content_url_regex = '/^https:\\/\\/(www\\.)?facebook\\.com\\//i';
    if (preg_match($content_url_regex, $data)) {
      return $data;
    }
    else {

      // Check if the user entered an iframe embed instead, and if so,
      // extract the post URL from the iframe src.
      $doc = new \DOMDocument();
      if (@$doc
        ->loadHTML($data)) {
        $iframes = $doc
          ->getElementsByTagName('iframe');
        if ($iframes->length > 0 && $iframes
          ->item(0)
          ->hasAttribute('src')) {
          $iframe_src = $iframes
            ->item(0)
            ->getAttribute('src');
          $uri_parts = parse_url($iframe_src);
          if ($uri_parts !== FALSE && isset($uri_parts['query'])) {
            parse_str($uri_parts['query'], $query_params);
            if (isset($query_params['href']) && preg_match($content_url_regex, $query_params['href'])) {
              return $query_params['href'];
            }
          }
        }
      }
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
    $display
      ->setComponent($this
      ->getSourceFieldDefinition($type)
      ->getName(), [
      'type' => 'facebook_embed',
      'label' => 'visually_hidden',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getSourceFieldConstraints() {
    return [
      'FacebookEmbedCode' => [],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
Facebook::$facebookFetcher protected property Facebook Fetcher.
Facebook::create public static function Creates an instance of the plugin. Overrides MediaSourceBase::create
Facebook::getFacebookUrl protected function Runs preg_match on embed code/URL.
Facebook::getMetadata public function Gets the value for a metadata attribute for a given media item. Overrides MediaSourceBase::getMetadata
Facebook::getMetadataAttributes public function Gets a list of metadata attributes provided by this plugin. Overrides MediaSourceInterface::getMetadataAttributes
Facebook::getSourceFieldConstraints public function Gets media source-specific validation constraints for a source field. Overrides MediaSourceFieldConstraintsInterface::getSourceFieldConstraints
Facebook::parseFacebookEmbedField public static function Extract a Facebook content URL from a string.
Facebook::prepareViewDisplay public function Prepares the media type fields for this source in the view display. Overrides MediaSourceBase::prepareViewDisplay
Facebook::__construct public function Constructs Facebook media source. Overrides MediaSourceBase::__construct
MediaSourceBase::$configFactory protected property The config factory service.
MediaSourceBase::$entityFieldManager protected property The entity field manager service.
MediaSourceBase::$entityTypeManager protected property The entity type manager service.
MediaSourceBase::$fieldTypeManager protected property The field type plugin manager service.
MediaSourceBase::$label protected property Plugin label.
MediaSourceBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
MediaSourceBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
MediaSourceBase::createSourceField public function Creates the source field definition for a type. Overrides MediaSourceInterface::createSourceField 2
MediaSourceBase::createSourceFieldStorage protected function Creates the source field storage definition.
MediaSourceBase::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 2
MediaSourceBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
MediaSourceBase::getSourceFieldDefinition public function Get the source field definition for a media type. Overrides MediaSourceInterface::getSourceFieldDefinition
MediaSourceBase::getSourceFieldName protected function Determine the name of the source field. 2
MediaSourceBase::getSourceFieldOptions protected function Get the source field options for the media type form.
MediaSourceBase::getSourceFieldStorage protected function Returns the source field storage definition.
MediaSourceBase::getSourceFieldValue public function Get the primary value stored in the source field. Overrides MediaSourceInterface::getSourceFieldValue
MediaSourceBase::prepareFormDisplay public function Prepares the media type fields for this source in the form display. Overrides MediaSourceInterface::prepareFormDisplay 3
MediaSourceBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
MediaSourceBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 1
MediaSourceBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 1
MediaSourceInterface::METADATA_FIELD_EMPTY constant Default empty value for metadata fields.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.