You are here

protected function WordPressItemMigration::replaceEmbeds in WordPress Migrate 7.2

Same name and namespace in other branches
  1. 7 wordpress_item.inc \WordPressItemMigration::replaceEmbeds()

If we have a YouTube or other media reference, replace it with media tags.

Parameters

array $matches:

File

./wordpress_item.inc, line 504
Support for migrating posts and pages from a WordPress blog into Drupal.

Class

WordPressItemMigration
Intermediate Migration class, implementing behavior common across different types (post_type) of items.

Code

protected function replaceEmbeds(array $matches) {

  // Default to the original <object> tag.
  $result = $matches[0];

  // If an <embed> tag is present, attempt to parse it.
  if ($matches[1]) {
    if (preg_match('|src=[\'"](.*?)[\'"]|i', $matches[1], $src_matches)) {
      $src = $src_matches[1];
    }
    else {
      return $result;
    }

    // Attempt to parse embedded media automatically through the media module.
    try {
      $uri = media_parse_to_uri($src);
      if ($uri) {

        // Sometimes, at least with oembed, it doesn't like the /v/ form
        $uri = str_replace('youtube.com/v/', 'youtube.com/watch?v=', $uri);
      }
    } catch (Exception $e) {
      return $result;
    }
    if (empty($uri)) {
      return $result;
    }

    // Extract the width & height for the media tag.
    if (preg_match('|width=[\'"](.*?)[\'"]|i', $matches[1], $width_matches)) {
      $width = $width_matches[1];
    }
    else {
      return $result;
    }
    if (preg_match('|height=[\'"](.*?)[\'"]|i', $matches[1], $height_matches)) {
      $height = $height_matches[1];
    }
    else {
      return $result;
    }

    // Build a file object suitable for saving.
    if (function_exists('file_uri_to_object')) {
      $file = file_uri_to_object($uri, TRUE);
      if (!isset($file->fid)) {

        // Save the media.
        file_save($file);
      }
    }
    else {

      // We shouldn't get here. But just in case...
      return $result;
    }

    // Build the media tag
    $video_info = array(
      'type' => 'media',
      'view_mode' => 'media_large',
      'fid' => $file->fid,
      'attributes' => array(
        'class' => 'media-image',
        'typeof' => 'foaf:Image',
        'height' => $height,
        'width' => $width,
        'style' => '',
      ),
    );
    $result = '[[' . drupal_json_encode($video_info) . ']]';
  }
  return $result;
}