ImageStyle.php 11.4 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\image\Entity\ImageStyle.
6 7
 */

8
namespace Drupal\image\Entity;
9 10

use Drupal\Core\Config\Entity\ConfigEntityBase;
11
use Drupal\Core\Entity\Annotation\EntityType;
12
use Drupal\Core\Annotation\Translation;
13
use Drupal\Core\Entity\EntityStorageControllerInterface;
14 15
use Drupal\image\ImageEffectBag;
use Drupal\image\ImageEffectInterface;
16
use Drupal\image\ImageStyleInterface;
17 18 19
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Url;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
20 21 22

/**
 * Defines an image style configuration entity.
23
 *
24
 * @EntityType(
25 26
 *   id = "image_style",
 *   label = @Translation("Image style"),
27
 *   controllers = {
28
 *     "form" = {
29 30
 *       "add" = "Drupal\image\Form\ImageStyleAddForm",
 *       "edit" = "Drupal\image\Form\ImageStyleEditForm",
31 32
 *       "delete" = "Drupal\image\Form\ImageStyleDeleteForm",
 *       "flush" = "Drupal\image\Form\ImageStyleFlushForm"
33
 *     },
34 35
 *     "storage" = "Drupal\Core\Config\Entity\ConfigStorageController",
 *     "list" = "Drupal\image\ImageStyleListController",
36
 *   },
37
 *   admin_permission = "administer image styles",
38 39 40 41 42
 *   config_prefix = "image.style",
 *   entity_keys = {
 *     "id" = "name",
 *     "label" = "label",
 *     "uuid" = "uuid"
43 44
 *   },
 *   links = {
45
 *     "edit-form" = "image.style_edit"
46 47
 *   }
 * )
48
 */
49
class ImageStyle extends ConfigEntityBase implements ImageStyleInterface {
50

51 52 53 54 55 56 57
  /**
   * The name of the image style to use as replacement upon delete.
   *
   * @var string
   */
  protected $replacementID;

58 59 60 61 62 63 64 65 66 67 68 69 70 71
  /**
   * The name of the image style.
   *
   * @var string
   */
  public $name;

  /**
   * The image style label.
   *
   * @var string
   */
  public $label;

72 73 74 75 76 77 78
  /**
   * The UUID for this entity.
   *
   * @var string
   */
  public $uuid;

79 80 81
  /**
   * The array of image effects for this image style.
   *
82
   * @var array
83
   */
84 85 86 87 88 89 90 91
  protected $effects = array();

  /**
   * Holds the collection of image effects that are used by this image style.
   *
   * @var \Drupal\image\ImageEffectBag
   */
  protected $effectsBag;
92 93 94 95 96 97 98 99

  /**
   * Overrides Drupal\Core\Entity\Entity::id().
   */
  public function id() {
    return $this->name;
  }

100 101 102 103
  /**
   * {@inheritdoc}
   */
  public function postSave(EntityStorageControllerInterface $storage_controller, $update = TRUE) {
104 105
    parent::postSave($storage_controller, $update);

106 107 108 109 110 111 112 113 114 115 116
    if ($update) {
      if (!empty($this->original) && $this->id() !== $this->original->id()) {
        // The old image style name needs flushing after a rename.
        $this->original->flush();
        // Update field instance settings if necessary.
        static::replaceImageStyle($this);
      }
      else {
        // Flush image style when updating without changing the name.
        $this->flush();
      }
117 118 119 120 121 122 123
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete(EntityStorageControllerInterface $storage_controller, array $entities) {
124 125
    parent::postDelete($storage_controller, $entities);

126 127
    foreach ($entities as $style) {
      // Flush cached media for the deleted style.
128
      $style->flush();
129 130 131 132 133 134 135 136 137 138 139 140 141 142
      // Check whether field instance settings need to be updated.
      // In case no replacement style was specified, all image fields that are
      // using the deleted style are left in a broken state.
      if ($new_id = $style->get('replacementID')) {
        // The deleted ID is still set as originalID.
        $style->set('name', $new_id);
        static::replaceImageStyle($style);
      }
    }
  }

  /**
   * Update field instance settings if the image style name is changed.
   *
143
   * @param \Drupal\image\ImageStyleInterface $style
144 145
   *   The image style.
   */
146
  protected static function replaceImageStyle(ImageStyleInterface $style) {
147
    if ($style->id() != $style->getOriginalId()) {
148 149 150 151 152 153 154 155
      // Loop through all entity displays looking for formatters / widgets using
      // the image style.
      foreach (entity_load_multiple('entity_display') as $display) {
        foreach ($display->getComponents() as $name => $options) {
          if (isset($options['type']) && $options['type'] == 'image' && $options['settings']['image_style'] == $style->getOriginalId()) {
            $options['settings']['image_style'] = $style->id();
            $display->setComponent($name, $options)
              ->save();
156
          }
157 158 159 160 161 162 163
        }
      }
      foreach (entity_load_multiple('entity_form_display') as $display) {
        foreach ($display->getComponents() as $name => $options) {
          if (isset($options['type']) && $options['type'] == 'image_image' && $options['settings']['preview_image_style'] == $style->getOriginalId()) {
            $options['settings']['preview_image_style'] = $style->id();
            $display->setComponent($name, $options)
164 165 166 167 168 169 170
              ->save();
          }
        }
      }
    }
  }

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
  /**
   * {@inheritdoc}
   */
  public function buildUri($uri) {
    $scheme = file_uri_scheme($uri);
    if ($scheme) {
      $path = file_uri_target($uri);
    }
    else {
      $path = $uri;
      $scheme = file_default_scheme();
    }
    return $scheme . '://styles/' . $this->id() . '/' . $scheme . '/' . $path;
  }

  /**
   * {@inheritdoc}
   */
  public function buildUrl($path, $clean_urls = NULL) {
    $uri = $this->buildUri($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
    // \Drupal\image\ImageStyleInterface::deliver()).
    $token_query = array();
    if (!\Drupal::config('image.settings')->get('suppress_itok_output')) {
202 203 204
      // The passed $path variable can be either a relative path or a full URI.
      $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
      $token_query = array(IMAGE_DERIVATIVE_TOKEN => $this->getPathToken($original_uri));
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
    }

    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 ? '&' : '?') . Url::buildQuery($token_query);
    }

    return $file_url;
  }

  /**
   * {@inheritdoc}
   */
  public function flush($path = NULL) {
    // A specific image path has been provided. Flush only that derivative.
    if (isset($path)) {
      $derivative_uri = $this->buildUri($path);
      if (file_exists($derivative_uri)) {
        file_unmanaged_delete($derivative_uri);
      }
246
      return $this;
247 248 249 250 251
    }

    // Delete the style directory in each registered wrapper.
    $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE);
    foreach ($wrappers as $wrapper => $wrapper_data) {
252 253 254
      if (file_exists($directory = $wrapper . '://styles/' . $this->id())) {
        file_unmanaged_delete_recursive($directory);
      }
255 256 257
    }

    // Let other modules update as necessary on flush.
258 259
    $module_handler = \Drupal::moduleHandler();
    $module_handler->invokeAll('image_style_flush', array($this));
260 261 262 263 264 265

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

    // Clear page caches when flushing.
266 267
    if ($module_handler->moduleExists('block')) {
      \Drupal::cache('block')->deleteAll();
268
    }
269 270
    \Drupal::cache('page')->deleteAll();
    return $this;
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
  }

  /**
   * {@inheritdoc}
   */
  public function createDerivative($original_uri, $derivative_uri) {
    // Get the folder for the final location of this style.
    $directory = drupal_dirname($derivative_uri);

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

286 287
    $image = \Drupal::service('image.factory')->get($original_uri);
    if (!$image->getResource()) {
288 289 290
      return FALSE;
    }

291 292
    foreach ($this->getEffects() as $effect) {
      $effect->applyEffect($image);
293 294
    }

295
    if (!$image->save($derivative_uri)) {
296 297 298 299 300 301 302 303 304 305 306 307 308
      if (file_exists($derivative_uri)) {
        watchdog('image', 'Cached image file %destination already exists. There may be an issue with your rewrite configuration.', array('%destination' => $derivative_uri), WATCHDOG_ERROR);
      }
      return FALSE;
    }

    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function transformDimensions(array &$dimensions) {
309 310
    foreach ($this->getEffects() as $effect) {
      $effect->transformDimensions($dimensions);
311 312 313 314 315 316 317 318 319 320
    }
  }

  /**
   * 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 $uri
321
   *   The URI of the original image of this style.
322 323 324 325 326
   *
   * @return string
   *   An eight-character token which can be used to protect image style
   *   derivatives against denial-of-service attacks.
   */
327
  public function getPathToken($uri) {
328 329 330 331
    // Return the first eight characters.
    return substr(Crypt::hmacBase64($this->id() . ':' . $uri, drupal_get_private_key() . drupal_get_hash_salt()), 0, 8);
  }

332 333 334 335
  /**
   * {@inheritdoc}
   */
  public function deleteImageEffect(ImageEffectInterface $effect) {
336
    $this->getEffects()->removeInstanceId($effect->getUuid());
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
    $this->save();
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getEffect($effect) {
    return $this->getEffects()->get($effect);
  }

  /**
   * {@inheritdoc}
   */
  public function getEffects() {
    if (!$this->effectsBag) {
      $this->effectsBag = new ImageEffectBag(\Drupal::service('plugin.manager.image.effect'), $this->effects);
354
      $this->effectsBag->sort();
355 356 357 358 359 360 361 362
    }
    return $this->effectsBag;
  }

  /**
   * {@inheritdoc}
   */
  public function saveImageEffect(array $configuration) {
363
    $effect_id = $this->getEffects()->updateConfiguration($configuration);
364 365 366 367 368 369 370 371 372
    $this->save();
    return $effect_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getExportProperties() {
    $properties = parent::getExportProperties();
373
    $properties['effects'] = $this->getEffects()->getConfiguration();
374 375 376
    return $properties;
  }

377
}