Newer
Older
<?php
/**
* @file
* Exposes global functionality for creating image styles.
*/
Alex Pott
committed
use Drupal\Core\Entity\EntityInterface;
Alex Pott
committed
use Drupal\Component\Plugin\Exception\UnknownPluginException;
use Drupal\field\Entity\Field;
use Drupal\field\Entity\FieldInstance;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\field\FieldInterface;
use Drupal\field\FieldInstanceInterface;
Angie Byron
committed
/**
* Image style constant for user presets in the database.
*/
Greg Dunlap
committed
const IMAGE_STORAGE_NORMAL = 1;
Angie Byron
committed
/**
* Image style constant for user presets that override module-defined presets.
*/
Greg Dunlap
committed
const IMAGE_STORAGE_OVERRIDE = 2;
Angie Byron
committed
/**
* Image style constant for module-defined presets in code.
*/
Greg Dunlap
committed
const IMAGE_STORAGE_DEFAULT = 4;
Angie Byron
committed
/**
* 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);
Angie Byron
committed
/**
* The name of the query parameter for image derivative tokens.
*/
define('IMAGE_DERIVATIVE_TOKEN', 'itok');
Angie Byron
committed
// Load all Field module hooks for Image.
require_once __DIR__ . '/image.field.inc';
Angie Byron
committed
/**
Angie Byron
committed
* Implements hook_help().
*/
function image_help($path, $arg) {
switch ($path) {
case 'admin/help#image':
$output = '';
Angie Byron
committed
$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>';
Angie Byron
committed
$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>';
Angie Byron
committed
$output .= '</dl>';
return $output;
Dries Buytaert
committed
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>';
Angie Byron
committed
case 'admin/config/media/image-styles/manage/%/add/%':
$effect = \Drupal::service('plugin.manager.image.effect')->getDefinition($arg[7]);
Alex Pott
committed
return isset($effect['description']) ? ('<p>' . $effect['description'] . '</p>') : NULL;
Angie Byron
committed
case 'admin/config/media/image-styles/manage/%/effects/%':
Alex Pott
committed
try {
$effect = entity_load('image_style', $arg[5])->getEffect($arg[7]);
}
catch (UnknownPluginException $e) {
return NULL;
}
$effect_definition = $effect->getPluginDefinition();
return isset($effect_definition['description']) ? ('<p>' . $effect_definition['description'] . '</p>') : NULL;
}
}
/**
Dries Buytaert
committed
* Implements hook_menu().
*/
function image_menu() {
$items = array();
Dries Buytaert
committed
$items['admin/config/media/image-styles'] = array(
'title' => 'Image styles',
'description' => 'Configure styles that can be used for resizing or adjusting images on display.',
'route_name' => 'image.style_list',
);
Dries Buytaert
committed
$items['admin/config/media/image-styles/list'] = array(
'title' => 'List',
'description' => 'List the current image styles on the site.',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
Angie Byron
committed
$items['admin/config/media/image-styles/manage/%image_style'] = array(
'title' => 'Edit style',
'description' => 'Configure an image style.',
'route_name' => 'image.style_edit',
);
Angie Byron
committed
$items['admin/config/media/image-styles/manage/%image_style/edit'] = array(
'title' => 'Edit',
'type' => MENU_DEFAULT_LOCAL_TASK,
);
Alex Pott
committed
$items['admin/config/media/image-styles/manage/%/effects/%'] = array(
'title' => 'Edit image effect',
'description' => 'Edit an existing effect within a style.',
'route_name' => 'image.effect_edit_form',
);
Alex Pott
committed
$items['admin/config/media/image-styles/manage/%image_style/effects/%/delete'] = array(
'title' => 'Delete image effect',
'description' => 'Delete an existing effect from a style.',
'route_name' => 'image.effect_delete',
);
Alex Pott
committed
$items['admin/config/media/image-styles/manage/%/add/%'] = array(
'title' => 'Add image effect',
'description' => 'Add a new effect to a style.',
'route_name' => 'image.effect_add_form',
);
return $items;
}
/**
Dries Buytaert
committed
* Implements hook_theme().
*/
function image_theme() {
return array(
Angie Byron
committed
// 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(
Dries Buytaert
committed
'style_name' => NULL,
'uri' => NULL,
'width' => NULL,
'height' => NULL,
Dries Buytaert
committed
'title' => NULL,
'attributes' => array(),
),
),
Angie Byron
committed
// Theme functions in image.admin.inc.
'image_style_effects' => array(
'render element' => 'form',
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_style_preview' => array(
'variables' => array('style' => NULL),
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_anchor' => array(
'render element' => 'element',
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_resize_summary' => array(
'variables' => array('data' => NULL),
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_scale_summary' => array(
'variables' => array('data' => NULL),
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_crop_summary' => array(
'variables' => array('data' => NULL),
Alex Pott
committed
'file' => 'image.admin.inc',
),
'image_rotate_summary' => array(
'variables' => array('data' => NULL),
Alex Pott
committed
'file' => 'image.admin.inc',
),
Angie Byron
committed
// Theme functions in image.field.inc.
'image_widget' => array(
'render element' => 'element',
Alex Pott
committed
'file' => 'image.field.inc',
Angie Byron
committed
),
Dries Buytaert
committed
'image_formatter' => array(
'variables' => array('item' => NULL, 'path' => NULL, 'image_style' => NULL),
Alex Pott
committed
'file' => 'image.field.inc',
Angie Byron
committed
),
);
}
/**
Dries Buytaert
committed
* 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.'),
),
);
}
/**
Dries Buytaert
committed
* Implements hook_file_download().
*
* Control the access to files underneath the styles directory.
*/
Angie Byron
committed
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);
Angie Byron
committed
// Discard "styles", style name, and scheme from the path
$args = array_slice($args, 3);
// Then the remaining parts are the path to the image.
Dries Buytaert
committed
$original_uri = file_uri_scheme($uri) . '://' . implode('/', $args);
// Check that the file exists and is an image.
$image = \Drupal::service('image.factory')->get($uri);
Alex Pott
committed
if ($image->isSupported()) {
// Check the permissions of the original to grant access to this image.
$headers = \Drupal::moduleHandler()->invokeAll('file_download', array($original_uri));
Angie Byron
committed
// Confirm there's at least one module granting access and none denying access.
if (!empty($headers) && !in_array(-1, $headers)) {
return array(
Dries Buytaert
committed
// Send headers describing the image's size, and MIME-type...
'Content-Type' => $image->getMimeType(),
'Content-Length' => $image->getFileSize(),
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.
);
}
}
return -1;
}
Angie Byron
committed
// 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));
Angie Byron
committed
if (count($files)) {
$file = reset($files);
if ($file->status) {
return file_file_download($uri, 'image');
}
}
}
/**
Dries Buytaert
committed
* Implements hook_file_move().
*/
Dries Buytaert
committed
function image_file_move(File $file, File $source) {
// Delete any image derivatives at the original image path.
image_path_flush($source->getFileUri());
}
/**
catch
committed
* Implements hook_file_predelete().
*/
Dries Buytaert
committed
function image_file_predelete(File $file) {
// Delete any image derivatives of this image.
image_path_flush($file->getFileUri());
}
/**
Jennifer Hodgdon
committed
* 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) {
Alex Pott
committed
$style->flush($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);
}
/**
Jennifer Hodgdon
committed
* Gets an array of image styles suitable for using as select list options.
*
* @param $include_empty
Angie Byron
committed
* 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)) {
Angie Byron
committed
$options[''] = t('- None -');
}
Angie Byron
committed
foreach ($styles as $name => $style) {
$options[$name] = $style->label();
Angie Byron
committed
}
if (empty($options)) {
$options[''] = t('No defined styles');
}
return $options;
}
/**
* Returns HTML for an image using a specific image style.
*
Dries Buytaert
committed
* @param $variables
* An associative array containing:
* - style_name: The name of the style to be used to alter the original image.
Greg Dunlap
committed
* - uri: The path of the image file relative to the Drupal files directory.
Dries Buytaert
committed
* This function does not work with images outside the files directory nor
Jennifer Hodgdon
committed
* 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. 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
Dries Buytaert
committed
* - 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
*/
Dries Buytaert
committed
function theme_image_style($variables) {
Alex Pott
committed
// @todo Image style loading will be moved outside theme in
// https://drupal.org/node/2029649
$style = entity_load('image_style', $variables['style_name']);
// Determine the dimensions of the styled image.
$dimensions = array(
'width' => $variables['width'],
'height' => $variables['height'],
);
Alex Pott
committed
$style->transformDimensions($dimensions);
// Add in the image style name as an HTML class.
$variables['attributes']['class'][] = 'image-style-' . drupal_html_class($variables['style_name']);
$image = array(
'#theme' => 'image',
'#width' => $dimensions['width'],
'#height' => $dimensions['height'],
'#attributes' => $variables['attributes'],
Alex Pott
committed
'#uri' => $style->buildUrl($variables['uri']),
);
if (isset($variables['alt']) || array_key_exists('alt', $variables)) {
$image['#alt'] = $variables['alt'];
}
if (isset($variables['title']) || array_key_exists('title', $variables)) {
$image['#title'] = $variables['title'];
}
return drupal_render($image);
}
/**
Jennifer Hodgdon
committed
* 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;
}
Alex Pott
committed
/**
* 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;
}
Alex Pott
committed
// Exit, if not saving an image field or image field instance entity.
if (!$field || $field->type != 'image') {
return;
}
if (!empty($entity->settings['default_image']['fid'][0])) {
$entity->settings['default_image']['fid'] = $entity->settings['default_image']['fid'][0];
}
if ($fid = $entity->settings['default_image']['fid']) {
$original_fid = isset($entity->original) ? $entity->original->settings['default_image']['fid'] : NULL;
if ($fid != $original_fid) {
$image = \Drupal::service('image.factory')->get(file_load($fid)->getFileUri());
$entity->settings['default_image']['width'] = $image->getWidth();
$entity->settings['default_image']['height'] = $image->getHeight();
Alex Pott
committed
}
}
Alex Pott
committed
else {
$entity->settings['default_image'] = array(
'fid' => NULL,
'alt' => '',
'title' => '',
'width' => NULL,
'height' => NULL,
);
}
Alex Pott
committed
}
/**
* Implements hook_ENTITY_TYPE_update() for 'field_entity'.
*/
function image_field_entity_update(FieldInterface $field) {
if ($field->type != 'image') {
// Only act on image fields.
return;
}
$prior_field = $field->original;
// The value of a managed_file element can be an array if #extended == TRUE.
Alex Pott
committed
$fid_new = isset($field->settings['default_image']['fid']['fids']) ? $field->settings['default_image']['fid']['fids'] : $field->settings['default_image']['fid'];
$fid_old = isset($prior_field->settings['default_image']['fid']['fids']) ? $prior_field->settings['default_image']['fid']['fids'] : $prior_field->settings['default_image']['fid'];
// Ensure that $fid_new and $fid_old are arrays, because the field setting
// 'default_image' key 'fid' might be the fallback value 0, see the annotation
// block of \Drupal\image\Plugin\Field\FieldType\ImageItem.
$fid_old = (array) $fid_old;
$fid_new = (array) $fid_new;
$file_new = $fid_new ? file_load(reset($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(reset($fid_old)))) {
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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->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_ENTITY_TYPE_update() for 'field_instance'.
*/
function image_field_instance_update(FieldInstanceInterface $field_instance) {
$field = $field_instance->getField();
if ($field->type != 'image') {
// Only act on image fields.
return;
}
$prior_instance = $field_instance->original;
// The value of a managed_file element can be an array if the #extended
// property is set to TRUE.
Alex Pott
committed
$fid_new = $field_instance->settings['default_image']['fid'];
if (isset($fid_new['fids'])) {
$fid_new = $fid_new['fids'];
}
Alex Pott
committed
$fid_old = $prior_instance->settings['default_image']['fid'];
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
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', $field_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', $field_instance->uuid);
}
}
// If the upload destination changed, then move the file.
if ($file_new && (file_uri_scheme($file_new->getFileUri()) != $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_ENTITY_TYPE_delete() for 'field_entity'.
*/
function image_field_entity_delete(FieldInterface $field) {
if ($field->type != 'image') {
// Only act on image fields.
return;
}
// The value of a managed_file element can be an array if #extended == TRUE.
Alex Pott
committed
$fid = (isset($field->settings['default_image']['fid']['fids']) ? $field->settings['default_image']['fid']['fids'] : $field->settings['default_image']['fid']);
if ($fid && ($file = file_load($fid[0]))) {
file_usage()->delete($file, 'image', 'default_image', $field->uuid);
}
}
/**
* Implements hook_ENTITY_TYPE_delete() for 'field_instance'.
*/
function image_field_instance_delete(FieldInstanceInterface $field_instance) {
$field = $field_instance->getField();
if ($field->type != 'image') {
// Only act on image fields.
return;
}
// The value of a managed_file element can be an array if the #extended
// property is set to TRUE.
Alex Pott
committed
$fid = $field_instance->settings['default_image']['fid'];
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', $field_instance->uuid);
}
}