You are here

media_feeds.module in Media Feeds 7.2

Same filename and directory in other branches
  1. 8 media_feeds.module
  2. 7 media_feeds.module

Implementation of the Feeds mapping API for the Media module.

File

media_feeds.module
View source
<?php

/**
 * @file
 * Implementation of the Feeds mapping API for the Media module.
 */

/**
 * Implements hook_feeds_processor_targets_alter().
 */
function media_feeds_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  if ($bundle_name === NULL) {
    return;
  }

  // Get the supported field types.
  $field_types = array();
  if (module_exists('mediafield')) {
    $field_types[] = 'media';
  }
  if (module_exists('file')) {
    $field_types[] = 'file';
  }
  if (module_exists('image')) {
    $field_types[] = 'image';
  }
  if (module_exists('video')) {
    $field_types[] = 'video';
  }
  foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
    $info = field_info_field($name);
    if (in_array($info['type'], $field_types)) {
      if (module_exists('media_internet')) {
        $targets[$name] = array(
          'name' => t('@label (media_internet)', array(
            '@label' => $instance['label'],
          )),
          'callback' => 'media_feeds_set_target',
          'description' => t('The @label field of the node. Value to be claimed by a Media Internet Sources provider. Be careful! The importing user will not need the @permission permission.', array(
            '@label' => $instance['label'],
            '@permission' => 'add media from remote sources',
          )),
        );
      }
      $targets[$name . ':MediaFeedsLibraryProvider'] = array(
        'name' => t('@label (by filename from library)', array(
          '@label' => $instance['label'],
        )),
        'callback' => 'media_feeds_set_target',
        'description' => t('The @label field of the node. Value is a filename existing in the Media library. The importing user will not need the permission to access existing files.', array(
          '@label' => $instance['label'],
        )),
        'summary_callback' => 'MediaFeedsLibraryProvider::summaryCallback',
        'form_callback' => 'MediaFeedsLibraryProvider::formCallback',
      );
      if (module_exists('remote_stream_wrapper')) {
        $targets[$name . ':MediaFeedsRemoteProvider'] = array(
          'name' => t('@label (remote_stream_wrapper)', array(
            '@label' => $instance['label'],
          )),
          'callback' => 'media_feeds_set_target',
          'description' => t('The @label field of the node. Value is a remote URI supported by remote_stream_wrapper. The file will be referenced from a remote server instead of downloading it to the local disc.', array(
            '@label' => $instance['label'],
          )),
        );
      }
    }
  }
}

/**
 * Do the actual mapping.
 */
function media_feeds_set_target($source, $entity, $target, $values, $config = array()) {
  if (empty($values)) {
    return;
  }
  if (!is_array($values)) {
    $values = array(
      $values,
    );
  }

  // Get the provider class name by splitting $target.
  // MediaFeedsInternetProvider is the default for the second value.
  list($target, $provider) = explode(':', $target, 2) + array(
    1 => 'MediaFeedsInternetProvider',
  );
  $field_info = field_info_field($target);
  $field = array(
    LANGUAGE_NONE => array(),
  );
  foreach ($values as $value) {
    try {

      // Find a provider to create a file object.
      $provider = new $provider($value, $config);

      // Validate and get a file object.
      $provider
        ->validate();
      $file = $provider
        ->getFileObject();
      if (!$file) {
        drupal_set_message(t('Failed to get the file object for %value.', array(
          '%value' => (string) $value,
        )));
        continue;
      }

      // Look for the field instance settings.
      $instance = field_info_instance($entity->feeds_item->entity_type, $target, $entity->type);

      // Validate the type.
      if ($field_info['type'] == 'media') {
        $allowed_types = $instance['widget']['settings']['allowed_types'];
      }
      elseif ($field_info['type'] == 'image') {
        $allowed_types = array(
          'image',
        );
      }
      if (!empty($allowed_types)) {
        $errors = media_file_validate_types($file, $allowed_types);
        if (count($errors)) {
          foreach ($errors as $error) {
            drupal_set_message(filter_xss($error), 'error');
          }
          continue;
        }
      }
      if (file_uri_scheme($file->uri) == 'temporary') {

        // Select the URI scheme that should be used to store a permanent copy
        // of a temporary file.
        if (in_array('public', $allowed_schemes)) {
          $destination = 'public';
        }
        elseif (in_array('private', $allowed_schemes)) {
          $destination = 'private';
        }
        else {
          $destination = reset($allowed_schemes);
        }
        if (!$destination) {
          drupal_set_message(t('Could not handle file with scheme <em>temporary://</em> because there is no scheme available for storing a permanent copy.'), 'error');
          continue;
        }

        // Copy file to a permanent location.
        $file->status = FILE_STATUS_PERMANENT;
        $file = file_copy($file, $destination . '://' . $file->basename);
        if (!$file) {
          drupal_set_message(t('Failed to copy file to a permanent location.'));
          continue;
        }
      }
      else {

        // Validate the URI scheme.
        // If public is allowed, also allow schemes supported by
        // MediaInternetFileHandler (http, ...).
        if ($field_info['type'] == 'media') {
          $allowed_schemes = $instance['widget']['settings']['allowed_schemes'];
          if (in_array('public', $allowed_schemes)) {
            $fromurlschemes = variable_get('media_fromurl_supported_schemes', array(
              'http',
              'https',
              'ftp',
              'smb',
              'ftps',
            ));
            foreach ($fromurlschemes as $fromurlscheme) {
              $allowed_schemes[$fromurlscheme] = $fromurlscheme;
            }
          }
          $scheme = file_uri_scheme($file->uri);
          if (!in_array($scheme, $allowed_schemes)) {
            drupal_set_message(t('Scheme %scheme not allowed for %target.', array(
              '%scheme' => $scheme . '://',
              '%target' => $target,
            )), 'error');
            continue;
          }
        }

        // Save file.
        $file = $provider
          ->save();
        if (!$file) {
          drupal_set_message(t('Failed to save the file.'), 'error');
          continue;
        }
      }

      // Apply author settings to the file.
      if (empty($file->uid) && !empty($entity->uid) || $file->uid != $entity->uid) {
        $file->uid = $entity->uid;
        if (!file_save($file)) {
          drupal_set_message(t('Failed to apply the author settings to the file.'), 'warning');
        }
      }

      // Attach the file to the field.
      $result = array(
        'fid' => $file->fid,
      );
      if ($field_info['type'] == 'file') {
        $result['display'] = (int) (!empty($field_info['settings']['display_default']));
      }
      $field[LANGUAGE_NONE][] = $result;
    } catch (MediaInternetNoHandlerException $e) {
      drupal_set_message($e
        ->getMessage(), 'error');
    } catch (MediaInternetValidationException $e) {
      drupal_set_message($e
        ->getMessage(), 'error');
    } catch (Exception $e) {
      drupal_set_message($e
        ->getMessage(), 'error');
    }
  }
  $entity->{$target} = $field;
}