You are here

function media_parse_to_file in D7 Media 7.4

Same name and namespace in other branches
  1. 7 media.module \media_parse_to_file()
  2. 7.2 media.module \media_parse_to_file()
  3. 7.3 media.module \media_parse_to_file()

Parse a URL or embed code and return a file object.

If a remote stream doesn't claim the parsed URL in media_parse_to_uri(), then we'll copy the file locally.

@NOTE The implementing modules may throw an error, which will not be caught here; it's up to the calling function to catch any thrown errors.

See also

media_parse_to_uri()

media_add_from_url_submit()

1 call to media_parse_to_file()
media_bulk_upload_import_batch_import_files in modules/media_bulk_upload/includes/media_bulk_upload.admin.inc
BatchAPI callback op for media import.

File

./media.module, line 612
Media API

Code

function media_parse_to_file($url, $params = array()) {
  try {
    $uri = media_parse_to_uri($url);
  } catch (Exception $e) {

    // Pass the error along.
    throw $e;
    return;
  }
  if (isset($uri)) {

    // Attempt to load an existing file from the unique URI.
    $select = db_select('file_managed', 'f')
      ->extend('PagerDefault')
      ->fields('f', array(
      'fid',
    ))
      ->condition('uri', $uri);
    $fid = $select
      ->execute()
      ->fetchCol();
    if (!empty($fid)) {
      $file = file_load(array_pop($fid));
      return $file;
    }
  }
  if (isset($uri)) {

    // The URL was successfully parsed to a URI, but does not yet have an
    // associated file: save it!
    $file = file_uri_to_object($uri);
    file_save($file);
  }
  else {

    // The URL wasn't parsed. We'll try to save a remote file.
    // Copy to temporary first.
    $source_uri = file_stream_wrapper_uri_normalize('temporary://' . basename($url));
    if (!@copy(@$url, $source_uri)) {
      throw new Exception('Unable to add file ' . $url);
    }
    $source_file = file_uri_to_object($source_uri);
    if (isset($params['to_directory'])) {
      $scheme = variable_get('file_default_scheme', 'public') . '://' . $params['to_directory'] . '/';
    }
    else {
      $scheme = variable_get('file_default_scheme', 'public') . '://';
    }
    $uri = file_stream_wrapper_uri_normalize($scheme . $source_file->filename);

    // Now to its new home.
    file_prepare_directory($scheme, FILE_CREATE_DIRECTORY || FILE_MODIFY_PERMISSIONS);
    $file = file_move($source_file, $uri, FILE_EXISTS_RENAME);
  }
  return $file;
}