You are here

function _amazons3_generate_image_style in AmazonS3 7.2

Generate an image style derivative and upload it to S3.

Parameters

S3Url $source: The URL of the source image stored in S3.

string $style: The name of the image style to generate the derivative for.

string $destination_temp: The temporary:// path to save the generated image in.

S3Url $destination_s3:

Return value

\stdClass The generated image object.

Throws

\Exception Thrown if image_style_create_derivative() failed.

1 call to _amazons3_generate_image_style()
amazons3_image_deliver in ./amazons3.module
Image delivery callback that uploads a derivative to S3.

File

./amazons3.module, line 196
Hook implementations for the AmazonS3 module.

Code

function _amazons3_generate_image_style(S3Url $source, $style, $destination_temp, S3Url $destination_s3) {

  // Before we create the file, we need to see if a row exists in
  // {files_managed}. This can happen when a temporary directory is cleared
  // by a server reboot or manually by a system administrator.
  $q = new EntityFieldQuery();
  $q
    ->entityCondition('entity_type', 'file')
    ->propertyCondition('uri', $destination_temp);
  $results = $q
    ->execute();
  if (!empty($results['file'])) {
    $file = reset($results['file']);
    $file = file_load($file->fid);
    file_delete($file);
  }

  // Generate the derivative.
  if (!image_style_create_derivative($style, $source, $destination_temp)) {

    // Something went horribly wrong, but all we have is a FALSE return. Throw
    // an exception with something useful.
    throw new \Exception('Amazon S3 was unable to create an image style derivative. Check the temporary directory configuration and permissions.');
  }

  // We need to manage our temporary file so it is cleaned by system_cron().
  $file = amazons3_file_create_object($destination_temp);
  file_save($file);

  // Register a shutdown function to upload the image to S3.
  $image = amazons3_image_load($destination_temp);
  register_shutdown_function(function () use ($image, $destination_s3) {

    // We have to call both of these to actually flush the image.
    ob_end_flush();
    flush();

    // file_unmanaged_copy() will not create any nested directories if
    // needed.
    $directory = drupal_dirname($destination_s3);
    if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
      watchdog('amazons3', 'Failed to create style directory: %directory', array(
        '%directory' => $directory,
      ), WATCHDOG_ERROR);
    }
    file_unmanaged_copy($image->source, $destination_s3);
  });
  return $image;
}