Skip to content
image.module 42.3 KiB
Newer Older
<?php

/**
 * @file
 * Exposes global functionality for creating image styles.
 */

/**
 * Image style constant for user presets in the database.
 */
define('IMAGE_STORAGE_NORMAL', 1);

/**
 * Image style constant for user presets that override module-defined presets.
 */
define('IMAGE_STORAGE_OVERRIDE', 2);

/**
 * Image style constant for module-defined presets in code.
 */
define('IMAGE_STORAGE_DEFAULT', 4);

/**
 * Image style constant to represent an editable preset.
 */
define('IMAGE_STORAGE_EDITABLE', IMAGE_STORAGE_NORMAL | IMAGE_STORAGE_OVERRIDE);

/**
 * Image style constant to represent any module-based preset.
 */
define('IMAGE_STORAGE_MODULE', IMAGE_STORAGE_OVERRIDE | IMAGE_STORAGE_DEFAULT);

// Load all Field module hooks for Image.
require_once DRUPAL_ROOT . '/modules/image/image.field.inc';

 */
function image_help($path, $arg) {
  switch ($path) {
    case 'admin/help#image':
      $output = '';
      $output .= '<p>' . t('The Image module allows you to manipulate images on your website. It exposes a setting for using the <em>Image toolkit</em>, allows you to configure <em>Image styles</em> that can be used for resizing or adjusting images on display, and provides an <em>Image</em> field for attaching images to content. For more information, see the online handbook entry for <a href="@image">Image module</a>.', array('@image' => 'http://drupal.org/documentation/modules/image')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Manipulating images') . '</dt>';
      $output .= '<dd>' . t('With the Image module you can scale, crop, resize, rotate and desaturate images without affecting the original image using <a href="@image">image styles</a>. When you change an image style, the module automatically refreshes all created images. Every image style must have a name, which will be used in the URL of the generated images. There are two common approaches to naming image styles (which you use will depend on how the image style is being applied):',array('@image' => url('admin/config/media/image-styles')));
      $output .= '<ul><li>' . t('Based on where it will be used: eg. <em>profile-picture</em>') . '</li>';
      $output .= '<li>' . t('Describing its appearance: eg. <em>square-85x85</em>') . '</li></ul>';
      $output .=  t('After you create an image style, you can add effects: crop, scale, resize, rotate, and desaturate (other contributed modules provide additional effects). For example, by combining effects as crop, scale, and desaturate, you can create square, grayscale thumbnails.') . '<dd>';
      $output .= '<dt>' . t('Attaching images to content as fields') . '</dt>';
      $output .= '<dd>' . t("Image module also allows you to attach images to content as fields. To add an image field to a <a href='@content-type'>content type</a>, go to the content type's <em>manage fields</em> page, and add a new field of type <em>Image</em>. Attaching images to content this way allows image styles to be applied and maintained, and also allows you more flexibility when theming.", array('@content-type' => url('admin/structure/types'))) . '</dd>';
      return '<p>' . t('Image styles commonly provide thumbnail sizes by scaling and cropping images, but can also add various effects before an image is displayed. When an image is displayed with a style, a new file is created and the original image is left unchanged.') . '</p>';
    case 'admin/config/media/image-styles/edit/%/add/%':
      $effect = image_effect_definition_load($arg[7]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
    case 'admin/config/media/image-styles/edit/%/effects/%':
      $effect = ($arg[5] == 'add') ? image_effect_definition_load($arg[6]) : image_effect_load($arg[6], $arg[4]);
      return isset($effect['help']) ? ('<p>' . $effect['help'] . '</p>') : NULL;
  }
}

  // Generate image derivatives of publicly available files.
  // If clean URLs are disabled, image derivatives will always be served
  // through the menu system.
  // If clean URLs are enabled and the image derivative already exists,
  // PHP will be bypassed.
  $directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
  $items[$directory_path . '/styles/%image_style'] = array(
    'page callback' => 'image_style_deliver',
    'page arguments' => array(count(explode('/', $directory_path)) + 1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  // Generate and deliver image derivatives of private files.
  // These image derivatives are always delivered through the menu system.
  $items['system/files/styles/%image_style'] = array(
    'title' => 'Generate image style',
    'page callback' => 'image_style_deliver',
    'page arguments' => array(3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/media/image-styles'] = array(
    'title' => 'Image styles',
    'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
    'page callback' => 'image_style_list',
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/list'] = array(
    'title' => 'List',
    'description' => 'List the current image styles on the site.',
    'page callback' => 'image_style_list',
    'access arguments' => array('administer image styles'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
  $items['admin/config/media/image-styles/add'] = array(
    'title' => 'Add style',
    'description' => 'Add a new image style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_add_form'),
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/edit/%image_style'] = array(
    'title' => 'Edit style',
    'description' => 'Configure an image style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_form', 5),
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/delete/%image_style'] = array(
    'title' => 'Delete style',
    'description' => 'Delete an image style.',
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_NORMAL),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_delete_form', 5),
    'access arguments' => array('administer image styles'),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/revert/%image_style'] = array(
    'title' => 'Revert style',
    'description' => 'Revert an image style.',
    'load arguments' => array(NULL, (string) IMAGE_STORAGE_OVERRIDE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_style_revert_form', 5),
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect'] = array(
    'description' => 'Edit an existing effect within a style.',
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_form', 5, 7),
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/edit/%image_style/effects/%image_effect/delete'] = array(
    'description' => 'Delete an existing effect from a style.',
    'load arguments' => array(5, (string) IMAGE_STORAGE_EDITABLE),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_delete_form', 5, 7),
    'access arguments' => array('administer image styles'),
  $items['admin/config/media/image-styles/edit/%image_style/add/%image_effect_definition'] = array(
    'title' => 'Add image effect',
    'description' => 'Add a new effect to a style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('image_effect_form', 5, 7),
    'access arguments' => array('administer image styles'),
        'attributes' => array(),
      ),
      'variables' => array('styles' => NULL),
      'variables' => array('style' => NULL),
      'variables' => array('data' => NULL),
      'variables' => array('data' => NULL),
      'variables' => array('data' => NULL),
      'variables' => array('data' => NULL),

    // Theme functions in image.field.inc.
    'image_widget' => array(
    'image_formatter' => array(
      'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
 */
function image_permission() {
  return array(
    'administer image styles' => array(
      'title' => t('Administer image styles'),
      'description' => t('Create and modify styles for generating image modifications such as thumbnails.'),
    ),
/**
 * Implements hook_form_FORM_ID_alter().
 */
function image_form_system_file_system_settings_alter(&$form, &$form_state) {
  $form['#submit'][] = 'image_system_file_system_settings_submit';
}

/**
 * Submit handler for the file system settings form.
 *
 * Adds a menu rebuild after the public file path has been changed, so that the
 * menu router item depending on that file path will be regenerated.
 */
function image_system_file_system_settings_submit($form, &$form_state) {
  if ($form['file_public_path']['#default_value'] !== $form_state['values']['file_public_path']) {
    variable_set('menu_rebuild_needed', TRUE);
  }
}

 */
function image_flush_caches() {
  return array('cache_image');
}

/**
 *
 * Control the access to files underneath the styles directory.
 */
function image_file_download($uri) {
  $path = file_uri_target($uri);

  // Private file access for image style derivatives.
  if (strpos($path, 'styles/') === 0) {
    $args = explode('/', $path);
    // Discard the first part of the path (styles).
    array_shift($args);
    // Get the style name from the second part.
    $style_name = array_shift($args);
    // Remove the scheme from the path.
    array_shift($args);

    // Then the remaining parts are the path to the image.
    $original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);

    // Check that the file exists and is an image.
      // Check the permissions of the original to grant access to this image.
      $headers = module_invoke_all('file_download', $original_uri);
      if (!in_array(-1, $headers)) {
        return array(
          // Send headers describing the image's size, and MIME-type...
          'Content-Type' => $info['mime_type'],
          'Content-Length' => $info['file_size'],
Angie Byron's avatar
Angie Byron committed
          // By not explicitly setting them here, this uses normal Drupal
          // Expires, Cache-Control and ETag headers to prevent proxy or
          // browser caching of private images.

  // Private file access for the original files. Note that we only
  // check access for non-temporary images, since file.module will
  // grant access for all temporary files.
  $files = file_load_multiple(array(), array('uri' => $uri));
  if (count($files)) {
    $file = reset($files);
    if ($file->status) {
      return file_file_download($uri, 'image');
    }
  }
 */
function image_file_move($file, $source) {
  // Delete any image derivatives at the original image path.
 */
function image_file_delete($file) {
  // Delete any image derivatives of this image.
 * Implements hook_image_default_styles().
 */
function image_image_default_styles() {
  $styles = array();

  $styles['thumbnail'] = array(
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 100, 'height' => 100, 'upscale' => 1),
        'weight' => 0,
      ),
    )
  );

  $styles['medium'] = array(
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 220, 'height' => 220, 'upscale' => 1),
        'weight' => 0,
      ),
    )
  );

  $styles['large'] = array(
    'effects' => array(
      array(
        'name' => 'image_scale',
        'data' => array('width' => 480, 'height' => 480, 'upscale' => 0),
/**
 * Implements hook_image_style_save().
 */
function image_image_style_save($style) {
  if (isset($style['old_name']) && $style['old_name'] != $style['name']) {
    $instances = field_read_instances();
    // Loop through all fields searching for image fields.
    foreach ($instances as $instance) {
      if ($instance['widget']['module'] == 'image') {
        $instance_changed = FALSE;
        foreach ($instance['display'] as $view_mode => $display) {
          // Check if the formatter involves an image style.
          if ($display['type'] == 'image' && $display['settings']['image_style'] == $style['old_name']) {
            // Update display information for any instance using the image
            // style that was just deleted.
            $instance['display'][$view_mode]['settings']['image_style'] = $style['name'];
            $instance_changed = TRUE;
          }
        }
        if ($instance['widget']['settings']['preview_image_style'] == $style['old_name']) {
          $instance['widget']['settings']['preview_image_style'] = $style['name'];
          $instance_changed = TRUE;
        }
        if ($instance_changed) {
          field_update_instance($instance);
        }
      }
    }
  }
}

/**
 * Implements hook_image_style_delete().
 */
function image_image_style_delete($style) {
  image_image_style_save($style);
}

/**
 * Implements hook_field_delete_field().
 */
function image_field_delete_field($field) {
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $fid = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  if ($fid && ($file = file_load($fid))) {
    file_usage_delete($file, 'image', 'default_image', $field['id']);
  }
}

/**
 * Implements hook_field_update_field().
 */
function image_field_update_field($field, $prior_field, $has_data) {
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $fid_new = (is_array($field['settings']['default_image']) ? $field['settings']['default_image']['fid'] : $field['settings']['default_image']);
  $fid_old = (is_array($prior_field['settings']['default_image']) ? $prior_field['settings']['default_image']['fid'] : $prior_field['settings']['default_image']);

  $file_new = $fid_new ? file_load($fid_new) : FALSE;

  if ($fid_new != $fid_old) {

    // Is there a new file?
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      file_save($file_new);
      file_usage_add($file_new, 'image', 'default_image', $field['id']);
    }

    // Is there an old file?
    if ($fid_old && ($file_old = file_load($fid_old))) {
      file_usage_delete($file_old, 'image', 'default_image', $field['id']);
    }
  }

  // If the upload destination changed, then move the file.
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Implements hook_field_delete_instance().
 */
function image_field_delete_instance($instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if the #extended
  // property is set to TRUE.
  $fid = $instance['settings']['default_image'];
  if (is_array($fid)) {
    $fid = $fid['fid'];
  }

  // Remove the default image when the instance is deleted.
  if ($fid && ($file = file_load($fid))) {
    file_usage_delete($file, 'image', 'default_image', $instance['id']);
  }
}

/**
 * Implements hook_field_update_instance().
 */
function image_field_update_instance($instance, $prior_instance) {
  // Only act on image fields.
  $field = field_read_field($instance['field_name']);
  if ($field['type'] != 'image') {
    return;
  }

  // The value of a managed_file element can be an array if the #extended
  // property is set to TRUE.
  $fid_new = $instance['settings']['default_image'];
  if (is_array($fid_new)) {
    $fid_new = $fid_new['fid'];
  }
  $fid_old = $prior_instance['settings']['default_image'];
  if (is_array($fid_old)) {
    $fid_old = $fid_old['fid'];
  }

  // If the old and new files do not match, update the default accordingly.
  $file_new = $fid_new ? file_load($fid_new) : FALSE;
  if ($fid_new != $fid_old) {
    // Save the new file, if present.
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      file_save($file_new);
      file_usage_add($file_new, 'image', 'default_image', $instance['id']);
    }
    // Delete the old file, if present.
    if ($fid_old && ($file_old = file_load($fid_old))) {
      file_usage_delete($file_old, 'image', 'default_image', $instance['id']);
    }
  }

  // If the upload destination changed, then move the file.
  if ($file_new && (file_uri_scheme($file_new->uri) != $field['settings']['uri_scheme'])) {
    $directory = $field['settings']['uri_scheme'] . '://default_images/';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Clear cached versions of a specific file in all styles.
 *
 * @param $path
 *   The Drupal file path to the original image.
 */
function image_path_flush($path) {
  $styles = image_styles();
  foreach ($styles as $style) {
    $image_path = image_style_path($style['name'], $path);
    if (file_exists($image_path)) {
      file_unmanaged_delete($image_path);
    }
  }
}

/**
 * Get an array of all styles and their settings.
 *
 * @return
 *   An array of styles keyed by the image style ID (isid).
 * @see image_style_load()
 */
function image_styles() {
  $styles = &drupal_static(__FUNCTION__);

  // Grab from cache or build the array.
  if (!isset($styles)) {
    if ($cache = cache_get('image_styles', 'cache')) {
      $styles = $cache->data;
    }
    else {
      $styles = array();

      // Select the module-defined styles.
      foreach (module_implements('image_default_styles') as $module) {
        $module_styles = module_invoke($module, 'image_default_styles');
        foreach ($module_styles as $style_name => $style) {
          $style['name'] = $style_name;
          $style['module'] = $module;
          $style['storage'] = IMAGE_STORAGE_DEFAULT;
          foreach ($style['effects'] as $key => $effect) {
            $definition = image_effect_definition_load($effect['name']);
            $effect = array_merge($definition, $effect);
          }
          $styles[$style_name] = $style;
        }
      }

      // Select all the user-defined styles.
      $user_styles = db_select('image_styles', NULL, array('fetch' => PDO::FETCH_ASSOC))
        ->fields('image_styles')
        ->orderBy('name')
        ->execute()
        ->fetchAllAssoc('name', PDO::FETCH_ASSOC);

      // Allow the user styles to override the module styles.
      foreach ($user_styles as $style_name => $style) {
        $style['module'] = NULL;
        $style['storage'] = IMAGE_STORAGE_NORMAL;
        $style['effects'] = image_style_effects($style);
        if (isset($styles[$style_name]['module'])) {
          $style['module'] = $styles[$style_name]['module'];
          $style['storage'] = IMAGE_STORAGE_OVERRIDE;
        }
        $styles[$style_name] = $style;
      cache_set('image_styles', $styles);
    }
  }

  return $styles;
}

/**
 * Load a style by style name or ID. May be used as a loader for menu items.
 *
 * @param $name
 *   The name of the style.
 * @param $isid
 *   Optional. The numeric id of a style if the name is not known.
 * @param $include
 *   If set, this loader will restrict to a specific type of image style, may be
 *   one of the defined Image style storage constants.
 * @return
 *   An image style array containing the following keys:
 *   - "isid": The unique image style ID.
 *   - "name": The unique image style name.
 *   - "effects": An array of image effects within this image style.
 *   If the image style name or ID is not valid, an empty array is returned.
function image_style_load($name = NULL, $isid = NULL, $include = NULL) {
  $styles = image_styles();

  // If retrieving by name.
  if (isset($name) && isset($styles[$name])) {
  if (!isset($name) && isset($isid)) {
    foreach ($styles as $name => $database_style) {
      if (isset($database_style['isid']) && $database_style['isid'] == $isid) {
  // Restrict to the specific type of flag. This bitwise operation basically
  // states "if the storage is X, then allow".
  if (isset($style) && (!isset($include) || ($style['storage'] & (int) $include))) {
    return $style;
  }

  // Otherwise the style was not found.
  return FALSE;
}

/**
 * Save an image style.
 *
 * @param style
 *   An image style array.
 * @return
 *   An image style array. In the case of a new style, 'isid' will be populated.
 */
function image_style_save($style) {
  if (isset($style['isid']) && is_numeric($style['isid'])) {
    // Load the existing style to make sure we account for renamed styles.
    $old_style = image_style_load(NULL, $style['isid']);
    image_style_flush($old_style);
    drupal_write_record('image_styles', $style, 'isid');
    if ($old_style['name'] != $style['name']) {
      $style['old_name'] = $old_style['name'];
    }
  }
  else {
    drupal_write_record('image_styles', $style);
    $style['is_new'] = TRUE;
  }

  // Let other modules update as necessary on save.
  module_invoke_all('image_style_save', $style);

  // Clear all caches and flush.
  image_style_flush($style);

  return $style;
}

/**
 * Delete an image style.
 *
 * @param $style
 *   An image style array.
 * @param $replacement_style_name
 *   (optional) When deleting a style, specify a replacement style name so
 *   that existing settings (if any) may be converted to a new style.
 * @return
 *   TRUE on success.
 */
function image_style_delete($style, $replacement_style_name = '') {
  image_style_flush($style);

  db_delete('image_effects')->condition('isid', $style['isid'])->execute();
  db_delete('image_styles')->condition('isid', $style['isid'])->execute();

  // Let other modules update as necessary on save.
  $style['old_name'] = $style['name'];
  $style['name'] = $replacement_style_name;
  module_invoke_all('image_style_delete', $style);

  return TRUE;
}

/**
 * Load all the effects for an image style.
 *
 * @param $style
 *   An image style array.
 * @return
 *   An array of image effects associated with specified image style in the
 *   format array('isid' => array()), or an empty array if the specified style
 *   has no effects.
 */
function image_style_effects($style) {
  $effects = image_effects();
  $style_effects = array();
  foreach ($effects as $effect) {
    if ($style['isid'] == $effect['isid']) {
      $style_effects[$effect['ieid']] = $effect;
    }
  }

  return $style_effects;
}

/**
 * Get an array of image styles suitable for using as select list options.
 *
 * @param $include_empty
 *   If TRUE a <none> option will be inserted in the options array.
 * @return
 *   Array of image styles both key and value are set to style name.
 */
function image_style_options($include_empty = TRUE) {
  $styles = image_styles();
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('<none>');
  }
  // Use the array concatenation operator '+' here instead of array_merge(),
  // because the latter loses the datatype of the array keys, turning
  // associative string keys into numeric ones without warning.
  $options = $options + drupal_map_assoc(array_keys($styles));
  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Menu callback; Given a style and image path, generate a derivative.
 *
 * After generating an image, transfer it to the requesting agent.
function image_style_deliver($style, $scheme) {
  // Check that the style is defined and the scheme is valid.
  if (!$style || !file_stream_wrapper_valid_scheme($scheme)) {
  $args = func_get_args();
  array_shift($args);
  array_shift($args);
  $target = implode('/', $args);

  $image_uri = $scheme . '://' . $target;
  $derivative_uri = image_style_path($style['name'], $image_uri);

  // If using the private scheme, let other modules provide headers and
  // control access to the file.
  if ($scheme == 'private') {
    if (file_exists($derivative_uri)) {
      file_download($scheme, file_uri_target($derivative_uri));
    }
    else {
      $headers = module_invoke_all('file_download', $image_uri);
      if (in_array(-1, $headers) || empty($headers)) {
        return drupal_access_denied();
      }
      if (count($headers)) {
        foreach ($headers as $name => $value) {
          drupal_add_http_header($name, $value);
        }
      }
    }
  }
  // Don't start generating the image if the derivative already exists or if
  // generation is in progress in another thread.
  $lock_name = 'image_style_deliver:' . $style['name'] . ':' . drupal_hash_base64($image_uri);
  if (!file_exists($derivative_uri)) {
    $lock_acquired = lock_acquire($lock_name);
    if (!$lock_acquired) {
      // Tell client to retry again in 3 seconds. Currently no browsers are known
      // to support Retry-After.
      drupal_add_http_header('Status', '503 Service Unavailable');
      drupal_add_http_header('Retry-After', 3);
      print t('Image generation in progress. Try again shortly.');
  // Try to generate the image, unless another thread just did it while we were
  // acquiring the lock.
  $success = file_exists($derivative_uri) || image_style_create_derivative($style, $image_uri, $derivative_uri);
    file_transfer($image->source, array('Content-Type' => $image->info['mime_type'], 'Content-Length' => $image->info['file_size']));
    watchdog('image', 'Unable to generate the derived image located at %path.', array('%path' => $derivative_uri));
    drupal_add_http_header('Status', '500 Internal Server Error');
 * Creates a new image derivative based on an image style.
 *
 * Generates an image derivative by creating the destination folder (if it does
 * not already exist), applying all image effects defined in $style['effects'],
 * and saving a cached version of the resulting image.
 *
 * @param $style
 *   An image style array.
 * @param $source
 *   Path of the source file.
 * @param $destination
 *   Path or URI of the destination file.
 *   TRUE if an image derivative was generated, or FALSE if the image derivative
 *   could not be generated.
 *
 * @see image_style_load()
 */
function image_style_create_derivative($style, $source, $destination) {
  // Get the folder for the final location of this style.
  $directory = drupal_dirname($destination);

  // Build the destination folder tree if it doesn't already exist.
  if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
    watchdog('image', 'Failed to create style directory: %directory', array('%directory' => $directory), WATCHDOG_ERROR);
    return FALSE;
  }

  if (!$image = image_load($source)) {
    return FALSE;
  }

  foreach ($style['effects'] as $effect) {
    image_effect_apply($image, $effect);
  }

  if (!image_save($image, $destination)) {
    if (file_exists($destination)) {
      watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $destination), WATCHDOG_ERROR);
    }
    return FALSE;
  }

  return TRUE;
}

/**
 * Determines the dimensions of the styled image.
 *
 * Applies all of an image style's effects to $dimensions.
 *
 * @param $style_name
 *   The name of the style to be applied.
 * @param $dimensions
 *   Dimensions to be modified - an array with components width and height, in
 *   pixels.
 */
function image_style_transform_dimensions($style_name, array &$dimensions) {
  module_load_include('inc', 'image', 'image.effects');
  $style = image_style_load($style_name);

  if (!is_array($style)) {
    return;
  }

  foreach ($style['effects'] as $effect) {
    if (isset($effect['dimensions passthrough'])) {
      continue;
    }

    if (isset($effect['dimensions callback'])) {
      $effect['dimensions callback']($dimensions, $effect['data']);
    }
    else {
      $dimensions['width'] = $dimensions['height'] = NULL;
    }
  }
}

/**
 * Flush cached media for a style.
 *
 * @param $style
 *   An image style array.
 */
function image_style_flush($style) {
  $style_directory = drupal_realpath(file_default_scheme() . '://styles/' . $style['name']);
  if (is_dir($style_directory)) {
    file_unmanaged_delete_recursive($style_directory);
  }

  // Let other modules update as necessary on flush.
  module_invoke_all('image_style_flush', $style);

  // Clear image style and effect caches.
  cache_clear_all('image_styles', 'cache');
  cache_clear_all('image_effects:', 'cache', TRUE);
  drupal_static_reset('image_styles');
  drupal_static_reset('image_effects');

  // Clear field caches so that formatters may be added for this style.
  field_info_cache_clear();
  drupal_theme_rebuild();

  // Clear page caches when flushing.
  if (module_exists('block')) {
    cache_clear_all('*', 'cache_block', TRUE);
  }
  cache_clear_all('*', 'cache_page', TRUE);
}

/**
 * Return the URL for an image derivative given a style and image path.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
 * @param $path
 *   The path to the image.
 * @return
 *   The absolute URL where a style image can be downloaded, suitable for use
 *   in an <img> tag. Requesting the URL will cause the image to be created.
  $uri = image_style_path($style_name, $path);

  // If not using clean URLs, the image derivative callback is only available
  // with the query string. If the file does not exist, use url() to ensure
  // that it is included. Once the file exists it's fine to fall back to the
  // actual file path, this avoids bootstrapping PHP once the files are built.
  if (!variable_get('clean_url') && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
    $directory_path = file_stream_wrapper_get_instance_by_uri($uri)->getDirectoryPath();
    return url($directory_path . '/' . file_uri_target($uri), array('absolute' => TRUE));
 * Return the URI of an image when using a style.
 *
 * The path returned by this function may not exist. The default generation
 * method only creates images when they are requested by a user's browser.
 *
 * @param $style_name
 *   The name of the style to be used with this image.
 * @param $uri
 *   The URI or path to the image.
function image_style_path($style_name, $uri) {
  $scheme = file_uri_scheme($uri);
  if ($scheme) {
    $path = file_uri_target($uri);
  }
  else {
    $path = $uri;
    $scheme = file_default_scheme();
  return $scheme . '://styles/' . $style_name . '/' . $scheme . '/' . $path;