image.module

Exposes global functionality for creating image styles.

File

drupal/core/modules/image/image.module
View source
<?php

/**
 * @file
 * Exposes global functionality for creating image styles.
 */
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\Language;
use Drupal\field\Plugin\Core\Entity\Field;
use Drupal\field\Plugin\Core\Entity\FieldInstance;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Uuid\Uuid;
use Drupal\file\Plugin\Core\Entity\File;
use Drupal\image\Plugin\Core\Entity\ImageStyle;

/**
 * Image style constant for user presets in the database.
 */
const IMAGE_STORAGE_NORMAL = 1;

/**
 * Image style constant for user presets that override module-defined presets.
 */
const IMAGE_STORAGE_OVERRIDE = 2;

/**
 * Image style constant for module-defined presets in code.
 */
const 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);

/**
 * The name of the query parameter for image derivative tokens.
 */
define('IMAGE_DERIVATIVE_TOKEN', 'itok');

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

/**
 * Implements hook_help().
 */
function image_help($path, $arg) {
  switch ($path) {
    case 'admin/help#image':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $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>';
      $output .= '</dl>';
      return $output;
    case 'admin/config/media/image-styles':
      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/manage/%/add/%':
      $effect = image_effect_definition_load($arg[7]);
      return isset($effect['help']) ? '<p>' . $effect['help'] . '</p>' : NULL;
    case 'admin/config/media/image-styles/manage/%/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;
  }
}

/**
 * Entity URI callback for image style.
 */
function image_style_entity_uri(ImageStyle $style) {
  return array(
    'path' => 'admin/config/media/image-styles/manage/' . $style
      ->id(),
  );
}

/**
 * Implements hook_menu().
 */
function image_menu() {
  $items = array();

  // 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(
    'title' => 'Generate image style',
    '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',
    ),
    'file' => 'image.admin.inc',
  );
  $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,
    'file' => 'image.admin.inc',
  );
  $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',
    ),
    'type' => MENU_LOCAL_ACTION,
    'weight' => 2,
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/manage/%image_style'] = array(
    'title' => 'Edit style',
    'title callback' => 'entity_page_label',
    'title arguments' => array(
      5,
    ),
    'description' => 'Configure an image style.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'image_style_form',
      5,
    ),
    'access arguments' => array(
      'administer image styles',
    ),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/manage/%image_style/edit'] = array(
    'title' => 'Edit',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/config/media/image-styles/manage/%image_style/delete'] = array(
    'title' => 'Delete',
    'description' => 'Delete an image style.',
    'type' => MENU_LOCAL_TASK,
    'weight' => 10,
    'route_name' => 'image_style_delete',
  );
  $items['admin/config/media/image-styles/manage/%image_style/effects/%image_effect'] = array(
    'title' => 'Edit image effect',
    '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',
    ),
    'file' => 'image.admin.inc',
  );
  $items['admin/config/media/image-styles/manage/%image_style/effects/%image_effect/delete'] = array(
    'title' => 'Delete image effect',
    'description' => 'Delete an existing effect from a style.',
    'route_name' => 'image_effect_delete',
  );
  $items['admin/config/media/image-styles/manage/%image_style/add/%image_effect_definition'] = array(
    'title' => 'Add image effect',
    'description' => 'Add a new effect to a style.',
    'load arguments' => array(
      5,
    ),
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'image_effect_form',
      5,
      7,
    ),
    'access arguments' => array(
      'administer image styles',
    ),
    'file' => 'image.admin.inc',
  );
  return $items;
}

/**
 * Implements hook_theme().
 */
function image_theme() {
  return array(
    // Theme functions in image.module.
    'image_style' => array(
      'variables' => array(
        'style_name' => NULL,
        'uri' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      ),
    ),
    // Theme functions in image.admin.inc.
    'image_style_list' => array(
      'variables' => array(
        'styles' => NULL,
      ),
    ),
    'image_style_effects' => array(
      'render element' => 'form',
    ),
    'image_style_preview' => array(
      'variables' => array(
        'style' => NULL,
      ),
    ),
    'image_anchor' => array(
      'render element' => 'element',
    ),
    'image_resize_summary' => array(
      'variables' => array(
        'data' => NULL,
      ),
    ),
    'image_scale_summary' => array(
      'variables' => array(
        'data' => NULL,
      ),
    ),
    'image_crop_summary' => array(
      'variables' => array(
        'data' => NULL,
      ),
    ),
    'image_rotate_summary' => array(
      'variables' => array(
        'data' => NULL,
      ),
    ),
    // Theme functions in image.field.inc.
    'image_widget' => array(
      'render element' => 'element',
    ),
    'image_formatter' => array(
      'variables' => array(
        'item' => NULL,
        'path' => NULL,
        'image_style' => NULL,
      ),
    ),
  );
}

/**
 * Implements hook_permission().
 */
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';
}

/**
 * Form submission handler for system_file_system_settings().
 *
 * 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']) {
    Drupal::state()
      ->set('menu_rebuild_needed', TRUE);
  }
}

/**
 * Implements hook_file_download().
 *
 * 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.
    if ($info = image_get_info($uri)) {

      // Check the permissions of the original to grant access to this image.
      $headers = module_invoke_all('file_download', $original_uri);

      // Confirm there's at least one module granting access and none denying access.
      if (!empty($headers) && !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'],
        );
      }
    }
    return -1;
  }

  // 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 = entity_load_multiple_by_properties('file', array(
    'uri' => $uri,
  ));
  if (count($files)) {
    $file = reset($files);
    if ($file->status) {
      return file_file_download($uri, 'image');
    }
  }
}

/**
 * Implements hook_file_move().
 */
function image_file_move(File $file, File $source) {

  // Delete any image derivatives at the original image path.
  image_path_flush($source->uri);
}

/**
 * Implements hook_file_predelete().
 */
function image_file_predelete(File $file) {

  // Delete any image derivatives of this image.
  image_path_flush($file->uri);
}

/**
 * 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 = isset($field['settings']['default_image']['fids']) ? $field['settings']['default_image']['fids'] : $field['settings']['default_image'];
  if ($fid && ($file = file_load($fid[0]))) {
    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 = isset($field['settings']['default_image']['fids']) ? $field['settings']['default_image']['fids'] : $field['settings']['default_image'];
  $fid_old = isset($prior_field['settings']['default_image']['fids']) ? $prior_field['settings']['default_image']['fids'] : $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_new
        ->save();
      file_usage()
        ->add($file_new, 'image', 'default_image', $field['uuid']);
    }

    // Is there an old file?
    if ($fid_old && ($file_old = file_load($fid_old[0]))) {
      file_usage()
        ->delete($file_old, 'image', 'default_image', $field['uuid']);
    }
  }

  // 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 (isset($fid_new['fids'])) {
    $fid_new = $fid_new['fids'];
  }
  $fid_old = $prior_instance['settings']['default_image'];
  if (isset($fid_old['fids'])) {
    $fid_old = $fid_old['fids'];
  }

  // If the old and new files do not match, update the default accordingly.
  $file_new = $fid_new ? file_load($fid_new[0]) : FALSE;
  if ($fid_new != $fid_old) {

    // Save the new file, if present.
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      $file_new
        ->save();
      file_usage()
        ->add($file_new, 'image', 'default_image', $instance['uuid']);
    }

    // Delete the old file, if present.
    if ($fid_old && ($file_old = file_load($fid_old[0]))) {
      file_usage()
        ->delete($file_old, 'image', 'default_image', $instance['uuid']);
    }
  }

  // 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);
  }
}

/**
 * Clears 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 = entity_load_multiple('image_style');
  foreach ($styles as $style) {
    $image_path = image_style_path($style
      ->id(), $path);
    if (file_exists($image_path)) {
      file_unmanaged_delete($image_path);
    }
  }
}

/**
 * Loads an ImageStyle object.
 *
 * @param string $name
 *   The ID of the ImageStyle object to load.
 */
function image_style_load($name) {
  return entity_load('image_style', $name);
}

/**
 * Gets 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 = entity_load_multiple('image_style');
  $options = array();
  if ($include_empty && !empty($styles)) {
    $options[''] = t('- None -');
  }
  foreach ($styles as $name => $style) {
    $options[$name] = $style
      ->label();
  }
  if (empty($options)) {
    $options[''] = t('No defined styles');
  }
  return $options;
}

/**
 * Page callback: Generates a derivative, given a style and image path.
 *
 * After generating an image, transfer it to the requesting agent.
 *
 * @param $style
 *   The image style
 */
function image_style_deliver($style, $scheme) {
  $args = func_get_args();
  array_shift($args);
  array_shift($args);
  $target = implode('/', $args);

  // Check that the style is defined, the scheme is valid, and the image
  // derivative token is valid. (Sites which require image derivatives to be
  // generated without a token can set the
  // 'image.settings:allow_insecure_derivatives' configuration to TRUE to bypass
  // the latter check, but this will increase the site's vulnerability to
  // denial-of-service attacks.)
  $valid = !empty($style) && file_stream_wrapper_valid_scheme($scheme);
  if (!config('image.settings')
    ->get('allow_insecure_derivatives')) {
    $valid = $valid && isset($_GET[IMAGE_DERIVATIVE_TOKEN]) && $_GET[IMAGE_DERIVATIVE_TOKEN] === image_style_path_token($style->name, $scheme . '://' . $target);
  }
  if (!$valid) {
    throw new AccessDeniedHttpException();
  }
  $image_uri = $scheme . '://' . $target;
  $derivative_uri = image_style_path($style
    ->id(), $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)) {
        throw new AccessDeniedHttpException();
      }
      if (count($headers)) {
        foreach ($headers as $name => $value) {
          drupal_add_http_header($name, $value);
        }
      }
    }
  }

  // Don't try to generate file if source is missing.
  if (!file_exists($image_uri)) {
    watchdog('image', 'Source image at %source_image_path not found while trying to generate derivative image at %derivative_path.', array(
      '%source_image_path' => $image_uri,
      '%derivative_path' => $derivative_uri,
    ));
    return new Response(t('Error generating image, missing source file.'), 404);
  }

  // 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
    ->id() . ':' . Crypt::hashBase64($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.
      throw new ServiceUnavailableHttpException(3, 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);
  if (!empty($lock_acquired)) {
    lock()
      ->release($lock_name);
  }
  if ($success) {
    $image = image_load($derivative_uri);
    $uri = $image->source;
    $headers = array(
      'Content-Type' => $image->info['mime_type'],
      'Content-Length' => $image->info['file_size'],
    );
    return new BinaryFileResponse($uri, 200, $headers);
  }
  else {
    watchdog('image', 'Unable to generate the derived image located at %path.', array(
      '%path' => $derivative_uri,
    ));
    return new Response(t('Error generating image.'), 500);
  }
}

/**
 * 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.
 *
 * @return
 *   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;
  }
  if (!empty($style->effects)) {
    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 = entity_load('image_style', $style_name);
  if (!empty($style->effects)) {
    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;
      }
    }
  }
}

/**
 * Flushes cached media for a style.
 *
 * @param $style
 *   An image style array.
 */
function image_style_flush($style) {

  // Delete the style directory in each registered wrapper.
  $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
  foreach ($wrappers as $wrapper => $wrapper_data) {
    file_unmanaged_delete_recursive($wrapper . '://styles/' . $style
      ->id());
  }

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

  // 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('block')
      ->deleteAll();
  }
  cache('page')
    ->deleteAll();
}

/**
 * Returns 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.
 * @param $clean_urls
 *   (optional) Whether clean URLs are in use.
 * @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.
 * @see image_style_deliver()
 */
function image_style_url($style_name, $path, $clean_urls = NULL) {
  $uri = image_style_path($style_name, $path);

  // The token query is added even if the
  // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so that
  // the emitted links remain valid if it is changed back to the default FALSE.
  // However, sites which need to prevent the token query from being emitted at
  // all can additionally set the 'image.settings:suppress_itok_output'
  // configuration to TRUE to achieve that (if both are set, the security token
  // will neither be emitted in the image derivative URL nor checked for in
  // image_style_deliver()).
  $token_query = array();
  if (!config('image.settings')
    ->get('suppress_itok_output')) {
    $token_query = array(
      IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)),
    );
  }
  if ($clean_urls === NULL) {

    // Assume clean URLs unless the request tells us otherwise.
    $clean_urls = TRUE;
    try {
      $request = Drupal::request();
      $clean_urls = $request->attributes
        ->get('clean_urls');
    } catch (ServiceNotFoundException $e) {
    }
  }

  // If not using clean URLs, the image derivative callback is only available
  // with the script path. 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 ($clean_urls === FALSE && 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,
      'query' => $token_query,
    ));
  }
  $file_url = file_create_url($uri);

  // Append the query string with the token, if necessary.
  if ($token_query) {
    $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($token_query);
  }
  return $file_url;
}

/**
 * Generates a token to protect an image style derivative.
 *
 * This prevents unauthorized generation of an image style derivative,
 * which can be costly both in CPU time and disk space.
 *
 * @param string $style_name
 *   The name of the image style.
 * @param string $uri
 *   The URI of the image for this style, for example as returned by
 *   image_style_path().
 *
 * @return string
 *   An eight-character token which can be used to protect image style
 *   derivatives against denial-of-service attacks.
 */
function image_style_path_token($style_name, $uri) {

  // Return the first eight characters.
  return substr(Crypt::hmacBase64($style_name . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
}

/**
 * Returns 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.
 * @return
 *   The URI to an image style image.
 * @see image_style_url()
 */
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;
}

/**
 * Returns a set of image effects.
 *
 * These image effects are exposed by modules implementing
 * hook_image_effect_info().
 *
 * @return
 *   An array of image effects to be used when transforming images.
 * @see hook_image_effect_info()
 * @see image_effect_definition_load()
 */
function image_effect_definitions() {
  $language_interface = language(Language::TYPE_INTERFACE);

  // hook_image_effect_info() includes translated strings, so each language is
  // cached separately.
  $langcode = $language_interface->langcode;
  $effects =& drupal_static(__FUNCTION__);
  if (!isset($effects)) {
    if ($cache = cache()
      ->get("image_effects:{$langcode}")) {
      $effects = $cache->data;
    }
    else {
      $effects = array();
      include_once __DIR__ . '/image.effects.inc';
      foreach (module_implements('image_effect_info') as $module) {
        foreach (module_invoke($module, 'image_effect_info') as $name => $effect) {

          // Ensure the current toolkit supports the effect.
          $effect['module'] = $module;
          $effect['name'] = $name;
          $effect['data'] = isset($effect['data']) ? $effect['data'] : array();
          $effects[$name] = $effect;
        }
      }
      uasort($effects, '_image_effect_definitions_sort');
      drupal_alter('image_effect_info', $effects);
      cache()
        ->set("image_effects:{$langcode}", $effects);
    }
  }
  return $effects;
}

/**
 * Loads the definition for an image effect.
 *
 * The effect definition is a set of core properties for an image effect, not
 * containing any user-settings. The definition defines various functions to
 * call when configuring or executing an image effect. This loader is mostly for
 * internal use within image.module. Use image_effect_load() or
 * entity_load() to get image effects that contain configuration.
 *
 * @param $effect
 *   The name of the effect definition to load.
 * @return
 *   An array containing the image effect definition with the following keys:
 *   - "effect": The unique name for the effect being performed. Usually prefixed
 *     with the name of the module providing the effect.
 *   - "module": The module providing the effect.
 *   - "help": A description of the effect.
 *   - "function": The name of the function that will execute the effect.
 *   - "form": (optional) The name of a function to configure the effect.
 *   - "summary": (optional) The name of a theme function that will display a
 *     one-line summary of the effect. Does not include the "theme_" prefix.
 */
function image_effect_definition_load($effect) {
  $definitions = image_effect_definitions();
  return isset($definitions[$effect]) ? $definitions[$effect] : FALSE;
}

/**
 * Loads a single image effect.
 *
 * @param $ieid
 *   The image effect ID.
 * @param $style_name
 *   The image style name.
 *
 * @return
 *   An image effect array, consisting of the following keys:
 *   - "ieid": The unique image effect ID.
 *   - "weight": The weight of this image effect within the image style.
 *   - "name": The name of the effect definition that powers this image effect.
 *   - "data": An array of configuration options for this image effect.
 *   Besides these keys, the entirety of the image definition is merged into
 *   the image effect array. Returns FALSE if the specified effect cannot be
 *   found.
 * @see image_effect_definition_load()
 */
function image_effect_load($ieid, $style_name) {
  if (($style = entity_load('image_style', $style_name)) && isset($style->effects[$ieid])) {
    $effect = $style->effects[$ieid];
    $definition = image_effect_definition_load($effect['name']);
    $effect = array_merge($definition, $effect);

    // @todo The effect's key name within the style is unknown. It *should* be
    //   identical to the ieid, but that is in no way guaranteed. And of course,
    //   the ieid key *within* the effect is senseless duplication in the first
    //   place. This problem can be eliminated in many places, but especially
    //   for loaded menu arguments like %image_effect, the actual router
    //   callbacks don't have access to 'ieid' anymore (unless resorting to
    //   dirty %index and %map tricks).
    $effect['ieid'] = $ieid;
    return $effect;
  }
  return FALSE;
}

/**
 * Saves an image effect.
 *
 * @param ImageStyle $style
 *   The image style this effect belongs to.
 * @param array $effect
 *   An image effect array. Passed by reference.
 *
 * @return array
 *   The saved image effect array. The 'ieid' key will be set for the effect.
 */
function image_effect_save($style, &$effect) {

  // Remove all values that are not properties of an image effect.
  // @todo Convert image effects into plugins.
  $effect = array_intersect_key($effect, array_flip(array(
    'ieid',
    'module',
    'name',
    'data',
    'weight',
  )));

  // Generate a unique image effect ID for a new effect.
  if (empty($effect['ieid'])) {
    $uuid = new Uuid();
    $effect['ieid'] = $uuid
      ->generate();
  }
  $style->effects[$effect['ieid']] = $effect;
  $style
    ->save();

  // Flush all derivatives that exist for this style, so they are regenerated
  // with the new or updated effect.
  image_style_flush($style);
}

/**
 * Deletes an image effect.
 *
 * @param ImageStyle $style
 *   The image style this effect belongs to.
 * @param $effect
 *   An image effect array.
 */
function image_effect_delete($style, $effect) {
  unset($style->effects[$effect['ieid']]);
  $style
    ->save();
  image_style_flush($style);
}

/**
 * Applies an image effect to the image object.
 *
 * @param $image
 *   An image object returned by image_load().
 * @param $effect
 *   An image effect array.
 * @return
 *   TRUE on success. FALSE if unable to perform the image effect on the image.
 */
function image_effect_apply($image, $effect) {
  module_load_include('inc', 'image', 'image.effects');
  $function = $effect['effect callback'];
  return $function($image, $effect['data']);
}

/**
 * Returns HTML for an image using a specific image style.
 *
 * @param $variables
 *   An associative array containing:
 *   - style_name: The name of the style to be used to alter the original image.
 *   - uri: The path of the image file relative to the Drupal files directory.
 *     This function does not work with images outside the files directory nor
 *     with remotely hosted images. This should be in a format such as
 *     'images/image.jpg', or using a stream wrapper such as
 *     'public://images/image.jpg'.
 *   - width: The width of the source image (if known).
 *   - height: The height of the source image (if known).
 *   - alt: The alternative text for text-based browsers.
 *   - title: The title text is displayed when the image is hovered in some
 *     popular browsers.
 *   - attributes: Associative array of attributes to be placed in the img tag.
 *
 * @ingroup themeable
 */
function theme_image_style($variables) {

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );
  image_style_transform_dimensions($variables['style_name'], $dimensions);
  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Add in the image style name as an HTML class.
  $variables['attributes']['class'][] = 'image-style-' . drupal_html_class($variables['style_name']);

  // Determine the URL for the styled image.
  $variables['uri'] = image_style_url($variables['style_name'], $variables['uri']);
  return theme('image', $variables);
}

/**
 * Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
 *
 * @param $value
 * @param $current_pixels
 * @param $new_pixels
 */
function image_filter_keyword($value, $current_pixels, $new_pixels) {
  switch ($value) {
    case 'top':
    case 'left':
      return 0;
    case 'bottom':
    case 'right':
      return $current_pixels - $new_pixels;
    case 'center':
      return $current_pixels / 2 - $new_pixels / 2;
  }
  return $value;
}

/**
 * Internal function for sorting image effect definitions through uasort().
 *
 * @see image_effect_definitions()
 */
function _image_effect_definitions_sort($a, $b) {
  return strcasecmp($a['name'], $b['name']);
}

/**
 * Implements hook_entity_presave().
 *
 * Transforms default image of image field from array into single value at save.
 */
function image_entity_presave(EntityInterface $entity, $type) {
  $field = FALSE;
  if ($entity instanceof FieldInstance) {
    $field = $entity
      ->getField();
  }
  elseif ($entity instanceof Field) {
    $field = $entity;
  }
  if ($field && $field->type == 'image' && is_array($entity->settings['default_image'])) {
    if (!empty($entity->settings['default_image'][0])) {
      $entity->settings['default_image'] = $entity->settings['default_image'][0];
    }
    else {
      $entity->settings['default_image'] = 0;
    }
  }
}

Functions

Namesort descending Description
image_effect_apply Applies an image effect to the image object.
image_effect_definitions Returns a set of image effects.
image_effect_definition_load Loads the definition for an image effect.
image_effect_delete Deletes an image effect.
image_effect_load Loads a single image effect.
image_effect_save Saves an image effect.
image_entity_presave Implements hook_entity_presave().
image_field_delete_field Implements hook_field_delete_field().
image_field_delete_instance Implements hook_field_delete_instance().
image_field_update_field Implements hook_field_update_field().
image_field_update_instance Implements hook_field_update_instance().
image_file_download Implements hook_file_download().
image_file_move Implements hook_file_move().
image_file_predelete Implements hook_file_predelete().
image_filter_keyword Accepts a keyword (center, top, left, etc) and returns it as a pixel offset.
image_form_system_file_system_settings_alter Implements hook_form_FORM_ID_alter().
image_help Implements hook_help().
image_menu Implements hook_menu().
image_path_flush Clears cached versions of a specific file in all styles.
image_permission Implements hook_permission().
image_style_create_derivative Creates a new image derivative based on an image style.
image_style_deliver Page callback: Generates a derivative, given a style and image path.
image_style_entity_uri Entity URI callback for image style.
image_style_flush Flushes cached media for a style.
image_style_load Loads an ImageStyle object.
image_style_options Gets an array of image styles suitable for using as select list options.
image_style_path Returns the URI of an image when using a style.
image_style_path_token Generates a token to protect an image style derivative.
image_style_transform_dimensions Determines the dimensions of the styled image.
image_style_url Returns the URL for an image derivative given a style and image path.
image_system_file_system_settings_submit Form submission handler for system_file_system_settings().
image_theme Implements hook_theme().
theme_image_style Returns HTML for an image using a specific image style.
_image_effect_definitions_sort Internal function for sorting image effect definitions through uasort().

Constants

Namesort descending Description
IMAGE_DERIVATIVE_TOKEN The name of the query parameter for image derivative tokens.
IMAGE_STORAGE_DEFAULT Image style constant for module-defined presets in code.
IMAGE_STORAGE_EDITABLE Image style constant to represent an editable preset.
IMAGE_STORAGE_MODULE Image style constant to represent any module-based preset.
IMAGE_STORAGE_NORMAL Image style constant for user presets in the database.
IMAGE_STORAGE_OVERRIDE Image style constant for user presets that override module-defined presets.