image.module 21.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
<?php

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

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\file\Entity\File;
use Drupal\field\FieldStorageConfigInterface;
use Drupal\field\FieldConfigInterface;
use Drupal\image\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($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.image':
      $field_ui_url = \Drupal::moduleHandler()->moduleExists('field_ui') ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#';

      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The Image module allows you to create fields that contain image files and to configure <a href=":image_styles">Image styles</a> that can be used to manipulate the display of images. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for terminology and general information on entities, fields, and how to create and manage fields. For more information, see the <a href=":image_documentation">online documentation for the Image module</a>.', array(':image_styles' => \Drupal::url('entity.image_style.collection'), ':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => $field_ui_url, ':image_documentation' => 'https://www.drupal.org/documentation/modules/image')) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dt>' . t('Defining image styles') . '</dt>';
      $output .= '<dd>' . t('The concept of image styles is that you can upload a single image but display it in several ways; each display variation, or <em>image style</em>, is the result of applying one or more <em>effects</em> to the original image. As an example, you might upload a high-resolution image with a 4:3 aspect ratio, and display it scaled down, square cropped, or black-and-white (or any combination of these effects). The Image module provides a way to do this efficiently: you configure an image style with the desired effects on the <a href=":image">Image styles page</a>, and the first time a particular image is requested in that style, the effects are applied. The resulting image is saved, and the next time that same style is requested, the saved image is retrieved without the need to recalculate the effects. Drupal core provides several effects that you can use to define styles; others may be provided by contributed modules.', array(':image' => \Drupal::url('entity.image_style.collection')));
      $output .= '<dt>' . t('Naming image styles') . '</dt>';
      $output .= '<dd>' . t('When you define an image style, you will need to choose a displayed name and a machine name. The displayed name is shown in administrative pages, and the machine name is used to generate the URL for accessing an image processed in that style. There are two common approaches to naming image styles: either based on the effects being applied (for example, <em>Square 85x85</em>), or based on where you plan to use it (for example, <em>Profile picture</em>).') . '</dd>';
      $output .= '<dt>' . t('Configuring image fields') . '</dt>';
      $output .= '<dd>' . t('A few of the settings for image fields are defined once when you create the field and cannot be changed later; these include the choice of public or private file storage and the number of images that can be stored in the field. The rest of the settings can be edited later; these settings include the field label, help text, allowed file extensions, image resolution restrictions, and the subdirectory in the public or private file storage where the images will be stored. The editable settings can also have different values for different entity sub-types; for instance, if your image field is used on both Page and Article content types, you can store the files in a different subdirectory for the two content types.') . '</dd>';
      $output .= '<dd>' . t('For accessibility and search engine optimization, all images that convey meaning on web sites should have alternate text. Drupal also allows entry of title text for images, but it can lead to confusion for screen reader users and its use is not recommended. Image fields can be configured so that alternate and title text fields are enabled or disabled; if enabled, the fields can be set to be required. The recommended setting is to enable and require alternate text and disable title text.') . '</dd>';
      $output .= '<dd>' . t('When you create an image field, you will need to choose whether the uploaded images will be stored in the public or private file directory defined in your settings.php file and shown on the <a href=":file-system">File system page</a>. This choice cannot be changed later. You can also configure your field to store files in a subdirectory of the public or private directory; this setting can be changed later and can be different for each entity sub-type using the field. For more information on file storage, see the <a href=":system-help">System module help page</a>.', array(':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', array('name' => 'system')))) . '</dd>';
      $output .= '<dd>' . t('The maximum file size that can be uploaded is limited by PHP settings of the server, but you can restrict it further by configuring a <em>Maximum upload size</em> in the field settings (this setting can be changed later). The maximum file size, either from PHP server settings or field configuration, is automatically displayed to users in the help text of the image field.') . '</dd>';
      $output .= '<dd>' . t('You can also configure a minimum and/or maximum resolution for uploaded images. Images that are too small will be rejected. Images that are to large will be resized. During the resizing the <a href=":exif">EXIF data</a> in the image will be lost.', array(':exif' => 'http://en.wikipedia.org/wiki/Exchangeable_image_file_format')) . '</dd>';
      $output .= '<dd>' . t('You can also configure a default image that will be used if no image is uploaded in an image field. This default can be defined for all instances of the field in the field storage settings when you create a field, and the setting can be overridden for each entity sub-type that uses the field.') . '</dd>';
      $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
      $output .= '<dd>' . t('On the <em>Manage display</em> page, you can choose the image formatter, which determines the image style used to display the image in each display mode and whether or not to display the image as a link. On the <em>Manage form display</em> page, you can configure the image upload widget, including setting the preview image style shown on the entity edit form.') . '</dd>';
      $output .= '</dl>';
      return $output;

    case 'entity.image_style.collection':
      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 'image.effect_add_form':
      $effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($route_match->getParameter('image_effect'));
      return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;

    case 'image.effect_edit_form':
      $effect = $route_match->getParameter('image_style')->getEffect($route_match->getParameter('image_effect'));
      $effect_definition = $effect->getPluginDefinition();
      return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
  }
}

/**
 * Implements hook_theme().
 */
function image_theme() {
  return array(
    // Theme functions in image.module.
    'image_style' => array(
      // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
      // allows the alt attribute to be omitted in some cases. Therefore,
      // default the alt attribute to an empty string, but allow code calling
      // _theme('image_style') to pass explicit NULL for it to be omitted.
      // Usually, neither omission nor an empty string satisfies accessibility
      // requirements, so it is strongly encouraged for code calling
      // _theme('image_style') to pass a meaningful value for the alt variable.
      // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
      // - http://www.w3.org/TR/xhtml1/dtds.html
      // - http://dev.w3.org/html5/spec/Overview.html#alt
      // The title attribute is optional in all cases, so it is omitted by
      // default.
      'variables' => array(
        'style_name' => NULL,
        'uri' => NULL,
        'width' => NULL,
        'height' => NULL,
        'alt' => '',
        'title' => NULL,
        'attributes' => array(),
      ),
    ),

    // Theme functions in image.admin.inc.
    'image_style_preview' => array(
      'variables' => array('style' => NULL),
      'file' => 'image.admin.inc',
    ),
    'image_anchor' => array(
      'render element' => 'element',
      'file' => 'image.admin.inc',
    ),
    'image_resize_summary' => array(
      'variables' => array('data' => NULL, 'effect' => array()),
    ),
    'image_scale_summary' => array(
      'variables' => array('data' => NULL, 'effect' => array()),
    ),
    'image_crop_summary' => array(
      'variables' => array('data' => NULL, 'effect' => array()),
    ),
    'image_rotate_summary' => array(
      'variables' => array('data' => NULL, 'effect' => array()),
    ),

    // Theme functions in image.field.inc.
    'image_widget' => array(
      'render element' => 'element',
      'file' => 'image.field.inc',
    ),
    'image_formatter' => array(
      'variables' => array('item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL),
      'file' => 'image.field.inc',
    ),
  );
}

/**
 * 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 "styles", style name, and scheme from the path
    $args = array_slice($args, 3);

    // 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.
    $image = \Drupal::service('image.factory')->get($uri);
    if ($image->isValid()) {
      // Check the permissions of the original to grant access to this image.
      $headers = \Drupal::moduleHandler()->invokeAll('file_download', array($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' => $image->getMimeType(),
          'Content-Length' => $image->getFileSize(),
          // 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.
        );
      }
    }
    return -1;
  }
}

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

/**
 * Implements hook_ENTITY_TYPE_predelete() for file entities.
 */
function image_file_predelete(File $file) {
  // Delete any image derivatives of this image.
  image_path_flush($file->getFileUri());
}

/**
 * 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 = ImageStyle::loadMultiple();
  foreach ($styles as $style) {
    $style->flush($path);
  }
}

/**
 * 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 = ImageStyle::loadMultiple();
  $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;
}

/**
 * Prepares variables for image style templates.
 *
 * Default template: image-style.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - width: The width of the image.
 *   - height: The height of the image.
 *   - style_name: The name of the image style to be applied.
 *   - attributes: Additional attributes to apply to the image.
 *   - uri: URI of the source image before styling.
 *   - alt: The alternative text for text-based browsers. HTML 4 and XHTML 1.0
 *     always require an alt attribute. The HTML 5 draft allows the alt
 *     attribute to be omitted in some cases. Therefore, this variable defaults
 *     to an empty string, but can be set to NULL for the attribute to be
 *     omitted. Usually, neither omission nor an empty string satisfies
 *     accessibility requirements, so it is strongly encouraged for code calling
 *     _theme('image_style') to pass a meaningful value for this variable.
 *     - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
 *     - http://www.w3.org/TR/xhtml1/dtds.html
 *     - http://dev.w3.org/html5/spec/Overview.html#alt
 *   - 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.
 */
function template_preprocess_image_style(&$variables) {
  $style = ImageStyle::load($variables['style_name']);

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

  $style->transformDimensions($dimensions, $variables['uri']);

  $variables['image'] = array(
    '#theme' => 'image',
    '#width' => $dimensions['width'],
    '#height' => $dimensions['height'],
    '#attributes' => $variables['attributes'],
    '#uri' => $style->buildUrl($variables['uri']),
    '#style_name' => $variables['style_name'],
  );

  if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
    $variables['image']['#alt'] = $variables['alt'];
  }
  if (isset($variables['title']) || array_key_exists('title', $variables)) {
    $variables['image']['#title'] = $variables['title'];
  }

}

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

/**
 * Implements hook_entity_presave().
 *
 * Transforms default image of image field from array into single value at save.
 */
function image_entity_presave(EntityInterface $entity) {
  // Get the default image settings, return if not saving an image field storage
  // or image field entity.
  $default_image = [];
  if (($entity instanceof FieldStorageConfigInterface || $entity instanceof FieldConfigInterface) && $entity->getType() == 'image') {
    $default_image = $entity->getSetting('default_image');
  }
  else {
    return;
  }

  if ($entity->isSyncing()) {
    return;
  }

  $uuid = $default_image['uuid'];
  if ($uuid) {
    $original_uuid = isset($entity->original) ? $entity->original->getSetting('default_image')['uuid'] : NULL;
    if ($uuid != $original_uuid) {
      $file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid);
      if ($file) {
        $image = \Drupal::service('image.factory')->get($file->getFileUri());
        $default_image['width'] = $image->getWidth();
        $default_image['height'] = $image->getHeight();
      }
      else {
        $default_image['uuid'] = NULL;
      }
    }
  }
  // Both FieldStorageConfigInterface and FieldConfigInterface have a
  // setSetting() method.
  $entity->setSetting('default_image', $default_image);
}

/**
 * Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.
 */
function image_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() != 'image') {
    // Only act on image fields.
    return;
  }

  $prior_field_storage = $field_storage->original;

  // The value of a managed_file element can be an array if #extended == TRUE.
  $uuid_new = $field_storage->getSetting('default_image')['uuid'];
  $uuid_old = $prior_field_storage->getSetting('default_image')['uuid'];

  $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;

  if ($uuid_new != $uuid_old) {

    // Is there a new file?
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      $file_new->save();
      \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field_storage->uuid());
    }

    // Is there an old file?
    if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
      \Drupal::service('file.usage')->delete($file_old, 'image', 'default_image', $field_storage->uuid());
    }
  }

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

/**
 * Implements hook_ENTITY_TYPE_update() for 'field_config'.
 */
function image_field_config_update(FieldConfigInterface $field) {
  $field_storage = $field->getFieldStorageDefinition();
  if ($field_storage->getType() != 'image') {
    // Only act on image fields.
    return;
  }

  $prior_instance = $field->original;

  $uuid_new = $field->getSetting('default_image')['uuid'];
  $uuid_old = $prior_instance->getSetting('default_image')['uuid'];

  // If the old and new files do not match, update the default accordingly.
  $file_new = $uuid_new ? \Drupal::entityManager()->loadEntityByUuid('file', $uuid_new) : FALSE;
  if ($uuid_new != $uuid_old) {
    // Save the new file, if present.
    if ($file_new) {
      $file_new->status = FILE_STATUS_PERMANENT;
      $file_new->save();
      \Drupal::service('file.usage')->add($file_new, 'image', 'default_image', $field->uuid());
    }
    // Delete the old file, if present.
    if ($uuid_old && ($file_old = \Drupal::entityManager()->loadEntityByUuid('file', $uuid_old))) {
      \Drupal::service('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->getFileUri()) != $field_storage->getSetting('uri_scheme'))) {
    $directory = $field_storage->getSetting('uri_scheme') . '://default_images/';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
    file_move($file_new, $directory . $file_new->filename);
  }
}

/**
 * Implements hook_ENTITY_TYPE_delete() for 'field_storage_config'.
 */
function image_field_storage_config_delete(FieldStorageConfigInterface $field) {
  if ($field->getType() != 'image') {
    // Only act on image fields.
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $uuid = $field->getSetting('default_image')['uuid'];
  if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
    \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  }
}

/**
 * Implements hook_ENTITY_TYPE_delete() for 'field_config'.
 */
function image_field_config_delete(FieldConfigInterface $field) {
  $field_storage = $field->getFieldStorageDefinition();
  if ($field_storage->getType() != 'image') {
    // Only act on image fields.
    return;
  }

  // The value of a managed_file element can be an array if #extended == TRUE.
  $uuid = $field->getSetting('default_image')['uuid'];

  // Remove the default image when the instance is deleted.
  if ($uuid && ($file = \Drupal::entityManager()->loadEntityByUuid('file', $uuid))) {
    \Drupal::service('file.usage')->delete($file, 'image', 'default_image', $field->uuid());
  }
}