You are here

public static function Facebook::parseFacebookEmbedField in Media entity facebook 8

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.

Parameters

string $data: The string that contains the Facebook post URL.

Return value

string|bool The post URL, or FALSE if one cannot be found.

2 calls to Facebook::parseFacebookEmbedField()
Facebook::getFacebookUrl in src/Plugin/MediaEntity/Type/Facebook.php
Runs preg_match on embed code/URL.
FacebookEmbedCodeConstraintValidator::validate in src/Plugin/Validation/Constraint/FacebookEmbedCodeConstraintValidator.php
Checks if the passed value is valid.

File

src/Plugin/MediaEntity/Type/Facebook.php, line 160

Class

Facebook
Provides media type plugin for Facebook.

Namespace

Drupal\media_entity_facebook\Plugin\MediaEntity\Type

Code

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;
}