fb096a7fdb295226b7cd06d7fd7517a96d633ccf
[yaffs-website] / web / core / modules / image / src / Entity / ImageStyle.php
1 <?php
2
3 namespace Drupal\image\Entity;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Config\Entity\ConfigEntityBase;
7 use Drupal\Core\Entity\EntityStorageInterface;
8 use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
9 use Drupal\Core\Routing\RequestHelper;
10 use Drupal\Core\Site\Settings;
11 use Drupal\Core\Url;
12 use Drupal\image\ImageEffectPluginCollection;
13 use Drupal\image\ImageEffectInterface;
14 use Drupal\image\ImageStyleInterface;
15 use Drupal\Component\Utility\Crypt;
16 use Drupal\Component\Utility\UrlHelper;
17 use Drupal\Core\StreamWrapper\StreamWrapperInterface;
18 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
19 use Drupal\Core\Entity\Entity\EntityViewDisplay;
20 /**
21  * Defines an image style configuration entity.
22  *
23  * @ConfigEntityType(
24  *   id = "image_style",
25  *   label = @Translation("Image style"),
26  *   handlers = {
27  *     "form" = {
28  *       "add" = "Drupal\image\Form\ImageStyleAddForm",
29  *       "edit" = "Drupal\image\Form\ImageStyleEditForm",
30  *       "delete" = "Drupal\image\Form\ImageStyleDeleteForm",
31  *       "flush" = "Drupal\image\Form\ImageStyleFlushForm"
32  *     },
33  *     "list_builder" = "Drupal\image\ImageStyleListBuilder",
34  *     "storage" = "Drupal\image\ImageStyleStorage",
35  *   },
36  *   admin_permission = "administer image styles",
37  *   config_prefix = "style",
38  *   entity_keys = {
39  *     "id" = "name",
40  *     "label" = "label"
41  *   },
42  *   links = {
43  *     "flush-form" = "/admin/config/media/image-styles/manage/{image_style}/flush",
44  *     "edit-form" = "/admin/config/media/image-styles/manage/{image_style}",
45  *     "delete-form" = "/admin/config/media/image-styles/manage/{image_style}/delete",
46  *     "collection" = "/admin/config/media/image-styles",
47  *   },
48  *   config_export = {
49  *     "name",
50  *     "label",
51  *     "effects",
52  *   }
53  * )
54  */
55 class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, EntityWithPluginCollectionInterface {
56
57   /**
58    * The name of the image style.
59    *
60    * @var string
61    */
62   protected $name;
63
64   /**
65    * The image style label.
66    *
67    * @var string
68    */
69   protected $label;
70
71   /**
72    * The array of image effects for this image style.
73    *
74    * @var array
75    */
76   protected $effects = [];
77
78   /**
79    * Holds the collection of image effects that are used by this image style.
80    *
81    * @var \Drupal\image\ImageEffectPluginCollection
82    */
83   protected $effectsCollection;
84
85   /**
86    * {@inheritdoc}
87    */
88   public function id() {
89     return $this->name;
90   }
91
92   /**
93    * {@inheritdoc}
94    */
95   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
96     parent::postSave($storage, $update);
97
98     if ($update) {
99       if (!empty($this->original) && $this->id() !== $this->original->id()) {
100         // The old image style name needs flushing after a rename.
101         $this->original->flush();
102         // Update field settings if necessary.
103         if (!$this->isSyncing()) {
104           static::replaceImageStyle($this);
105         }
106       }
107       else {
108         // Flush image style when updating without changing the name.
109         $this->flush();
110       }
111     }
112   }
113
114   /**
115    * {@inheritdoc}
116    */
117   public static function postDelete(EntityStorageInterface $storage, array $entities) {
118     parent::postDelete($storage, $entities);
119
120     /** @var \Drupal\image\ImageStyleInterface[] $entities */
121     foreach ($entities as $style) {
122       // Flush cached media for the deleted style.
123       $style->flush();
124       // Clear the replacement ID, if one has been previously stored.
125       /** @var \Drupal\image\ImageStyleStorageInterface $storage */
126       $storage->clearReplacementId($style->id());
127     }
128   }
129
130   /**
131    * Update field settings if the image style name is changed.
132    *
133    * @param \Drupal\image\ImageStyleInterface $style
134    *   The image style.
135    */
136   protected static function replaceImageStyle(ImageStyleInterface $style) {
137     if ($style->id() != $style->getOriginalId()) {
138       // Loop through all entity displays looking for formatters / widgets using
139       // the image style.
140       foreach (EntityViewDisplay::loadMultiple() as $display) {
141         foreach ($display->getComponents() as $name => $options) {
142           if (isset($options['type']) && $options['type'] == 'image' && $options['settings']['image_style'] == $style->getOriginalId()) {
143             $options['settings']['image_style'] = $style->id();
144             $display->setComponent($name, $options)
145               ->save();
146           }
147         }
148       }
149       foreach (EntityViewDisplay::loadMultiple() as $display) {
150         foreach ($display->getComponents() as $name => $options) {
151           if (isset($options['type']) && $options['type'] == 'image_image' && $options['settings']['preview_image_style'] == $style->getOriginalId()) {
152             $options['settings']['preview_image_style'] = $style->id();
153             $display->setComponent($name, $options)
154               ->save();
155           }
156         }
157       }
158     }
159   }
160
161   /**
162    * {@inheritdoc}
163    */
164   public function buildUri($uri) {
165     $source_scheme = $scheme = $this->fileUriScheme($uri);
166     $default_scheme = $this->fileDefaultScheme();
167
168     if ($source_scheme) {
169       $path = $this->fileUriTarget($uri);
170       // The scheme of derivative image files only needs to be computed for
171       // source files not stored in the default scheme.
172       if ($source_scheme != $default_scheme) {
173         $class = $this->getStreamWrapperManager()->getClass($source_scheme);
174         $is_writable = $class::getType() & StreamWrapperInterface::WRITE;
175
176         // Compute the derivative URI scheme. Derivatives created from writable
177         // source stream wrappers will inherit the scheme. Derivatives created
178         // from read-only stream wrappers will fall-back to the default scheme.
179         $scheme = $is_writable ? $source_scheme : $default_scheme;
180       }
181     }
182     else {
183       $path = $uri;
184       $source_scheme = $scheme = $default_scheme;
185     }
186     return "$scheme://styles/{$this->id()}/$source_scheme/{$this->addExtension($path)}";
187   }
188
189   /**
190    * {@inheritdoc}
191    */
192   public function buildUrl($path, $clean_urls = NULL) {
193     $uri = $this->buildUri($path);
194     // The token query is added even if the
195     // 'image.settings:allow_insecure_derivatives' configuration is TRUE, so
196     // that the emitted links remain valid if it is changed back to the default
197     // FALSE. However, sites which need to prevent the token query from being
198     // emitted at all can additionally set the
199     // 'image.settings:suppress_itok_output' configuration to TRUE to achieve
200     // that (if both are set, the security token will neither be emitted in the
201     // image derivative URL nor checked for in
202     // \Drupal\image\ImageStyleInterface::deliver()).
203     $token_query = [];
204     if (!\Drupal::config('image.settings')->get('suppress_itok_output')) {
205       // The passed $path variable can be either a relative path or a full URI.
206       $original_uri = file_uri_scheme($path) ? file_stream_wrapper_uri_normalize($path) : file_build_uri($path);
207       $token_query = [IMAGE_DERIVATIVE_TOKEN => $this->getPathToken($original_uri)];
208     }
209
210     if ($clean_urls === NULL) {
211       // Assume clean URLs unless the request tells us otherwise.
212       $clean_urls = TRUE;
213       try {
214         $request = \Drupal::request();
215         $clean_urls = RequestHelper::isCleanUrl($request);
216       }
217       catch (ServiceNotFoundException $e) {
218       }
219     }
220
221     // If not using clean URLs, the image derivative callback is only available
222     // with the script path. If the file does not exist, use Url::fromUri() to
223     // ensure that it is included. Once the file exists it's fine to fall back
224     // to the actual file path, this avoids bootstrapping PHP once the files are
225     // built.
226     if ($clean_urls === FALSE && file_uri_scheme($uri) == 'public' && !file_exists($uri)) {
227       $directory_path = $this->getStreamWrapperManager()->getViaUri($uri)->getDirectoryPath();
228       return Url::fromUri('base:' . $directory_path . '/' . file_uri_target($uri), ['absolute' => TRUE, 'query' => $token_query])->toString();
229     }
230
231     $file_url = file_create_url($uri);
232     // Append the query string with the token, if necessary.
233     if ($token_query) {
234       $file_url .= (strpos($file_url, '?') !== FALSE ? '&' : '?') . UrlHelper::buildQuery($token_query);
235     }
236
237     return $file_url;
238   }
239
240   /**
241    * {@inheritdoc}
242    */
243   public function flush($path = NULL) {
244     // A specific image path has been provided. Flush only that derivative.
245     if (isset($path)) {
246       $derivative_uri = $this->buildUri($path);
247       if (file_exists($derivative_uri)) {
248         file_unmanaged_delete($derivative_uri);
249       }
250       return $this;
251     }
252
253     // Delete the style directory in each registered wrapper.
254     $wrappers = $this->getStreamWrapperManager()->getWrappers(StreamWrapperInterface::WRITE_VISIBLE);
255     foreach ($wrappers as $wrapper => $wrapper_data) {
256       if (file_exists($directory = $wrapper . '://styles/' . $this->id())) {
257         file_unmanaged_delete_recursive($directory);
258       }
259     }
260
261     // Let other modules update as necessary on flush.
262     $module_handler = \Drupal::moduleHandler();
263     $module_handler->invokeAll('image_style_flush', [$this]);
264
265     // Clear caches so that formatters may be added for this style.
266     drupal_theme_rebuild();
267
268     Cache::invalidateTags($this->getCacheTagsToInvalidate());
269
270     return $this;
271   }
272
273   /**
274    * {@inheritdoc}
275    */
276   public function createDerivative($original_uri, $derivative_uri) {
277
278     // If the source file doesn't exist, return FALSE without creating folders.
279     $image = \Drupal::service('image.factory')->get($original_uri);
280     if (!$image->isValid()) {
281       return FALSE;
282     }
283
284     // Get the folder for the final location of this style.
285     $directory = drupal_dirname($derivative_uri);
286
287     // Build the destination folder tree if it doesn't already exist.
288     if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
289       \Drupal::logger('image')->error('Failed to create style directory: %directory', ['%directory' => $directory]);
290       return FALSE;
291     }
292
293     foreach ($this->getEffects() as $effect) {
294       $effect->applyEffect($image);
295     }
296
297     if (!$image->save($derivative_uri)) {
298       if (file_exists($derivative_uri)) {
299         \Drupal::logger('image')->error('Cached image file %destination already exists. There may be an issue with your rewrite configuration.', ['%destination' => $derivative_uri]);
300       }
301       return FALSE;
302     }
303
304     return TRUE;
305   }
306
307   /**
308    * {@inheritdoc}
309    */
310   public function transformDimensions(array &$dimensions, $uri) {
311     foreach ($this->getEffects() as $effect) {
312       $effect->transformDimensions($dimensions, $uri);
313     }
314   }
315
316   /**
317    * {@inheritdoc}
318    */
319   public function getDerivativeExtension($extension) {
320     foreach ($this->getEffects() as $effect) {
321       $extension = $effect->getDerivativeExtension($extension);
322     }
323     return $extension;
324   }
325
326   /**
327    * {@inheritdoc}
328    */
329   public function getPathToken($uri) {
330     // Return the first 8 characters.
331     return substr(Crypt::hmacBase64($this->id() . ':' . $this->addExtension($uri), $this->getPrivateKey() . $this->getHashSalt()), 0, 8);
332   }
333
334   /**
335    * {@inheritdoc}
336    */
337   public function deleteImageEffect(ImageEffectInterface $effect) {
338     $this->getEffects()->removeInstanceId($effect->getUuid());
339     $this->save();
340     return $this;
341   }
342
343   /**
344    * {@inheritdoc}
345    */
346   public function getEffect($effect) {
347     return $this->getEffects()->get($effect);
348   }
349
350   /**
351    * {@inheritdoc}
352    */
353   public function getEffects() {
354     if (!$this->effectsCollection) {
355       $this->effectsCollection = new ImageEffectPluginCollection($this->getImageEffectPluginManager(), $this->effects);
356       $this->effectsCollection->sort();
357     }
358     return $this->effectsCollection;
359   }
360
361   /**
362    * {@inheritdoc}
363    */
364   public function getPluginCollections() {
365     return ['effects' => $this->getEffects()];
366   }
367
368   /**
369    * {@inheritdoc}
370    */
371   public function addImageEffect(array $configuration) {
372     $configuration['uuid'] = $this->uuidGenerator()->generate();
373     $this->getEffects()->addInstanceId($configuration['uuid'], $configuration);
374     return $configuration['uuid'];
375   }
376
377   /**
378    * {@inheritdoc}
379    */
380   public function getReplacementID() {
381     /** @var \Drupal\image\ImageStyleStorageInterface $storage */
382     $storage = $this->entityTypeManager()->getStorage($this->getEntityTypeId());
383     return $storage->getReplacementId($this->id());
384   }
385
386   /**
387    * {@inheritdoc}
388    */
389   public function getName() {
390     return $this->get('name');
391   }
392
393   /**
394    * {@inheritdoc}
395    */
396   public function setName($name) {
397     $this->set('name', $name);
398     return $this;
399   }
400
401   /**
402    * Returns the image effect plugin manager.
403    *
404    * @return \Drupal\Component\Plugin\PluginManagerInterface
405    *   The image effect plugin manager.
406    */
407   protected function getImageEffectPluginManager() {
408     return \Drupal::service('plugin.manager.image.effect');
409   }
410
411   /**
412    * Gets the Drupal private key.
413    *
414    * @return string
415    *   The Drupal private key.
416    */
417   protected function getPrivateKey() {
418     return \Drupal::service('private_key')->get();
419   }
420
421   /**
422    * Gets a salt useful for hardening against SQL injection.
423    *
424    * @return string
425    *   A salt based on information in settings.php, not in the database.
426    *
427    * @throws \RuntimeException
428    */
429   protected function getHashSalt() {
430     return Settings::getHashSalt();
431   }
432
433   /**
434    * Adds an extension to a path.
435    *
436    * If this image style changes the extension of the derivative, this method
437    * adds the new extension to the given path. This way we avoid filename
438    * clashes while still allowing us to find the source image.
439    *
440    * @param string $path
441    *   The path to add the extension to.
442    *
443    * @return string
444    *   The given path if this image style doesn't change its extension, or the
445    *   path with the added extension if it does.
446    */
447   protected function addExtension($path) {
448     $original_extension = pathinfo($path, PATHINFO_EXTENSION);
449     $extension = $this->getDerivativeExtension($original_extension);
450     if ($original_extension !== $extension) {
451       $path .= '.' . $extension;
452     }
453     return $path;
454   }
455
456   /**
457    * Provides a wrapper for file_uri_scheme() to allow unit testing.
458    *
459    * Returns the scheme of a URI (e.g. a stream).
460    *
461    * @param string $uri
462    *   A stream, referenced as "scheme://target"  or "data:target".
463    *
464    * @see file_uri_target()
465    *
466    * @todo: Remove when https://www.drupal.org/node/2050759 is in.
467    *
468    * @return string
469    *   A string containing the name of the scheme, or FALSE if none. For
470    *   example, the URI "public://example.txt" would return "public".
471    */
472   protected function fileUriScheme($uri) {
473     return file_uri_scheme($uri);
474   }
475
476   /**
477    * Provides a wrapper for file_uri_target() to allow unit testing.
478    *
479    * Returns the part of a URI after the schema.
480    *
481    * @param string $uri
482    *   A stream, referenced as "scheme://target" or "data:target".
483    *
484    * @see file_uri_scheme()
485    *
486    * @todo: Convert file_uri_target() into a proper injectable service.
487    *
488    * @return string|bool
489    *   A string containing the target (path), or FALSE if none.
490    *   For example, the URI "public://sample/test.txt" would return
491    *   "sample/test.txt".
492    */
493   protected function fileUriTarget($uri) {
494     return file_uri_target($uri);
495   }
496
497   /**
498    * Provides a wrapper for file_default_scheme() to allow unit testing.
499    *
500    * Gets the default file stream implementation.
501    *
502    * @todo: Convert file_default_scheme() into a proper injectable service.
503    *
504    * @return string
505    *   'public', 'private' or any other file scheme defined as the default.
506    */
507   protected function fileDefaultScheme() {
508     return file_default_scheme();
509   }
510
511   /**
512    * Gets the stream wrapper manager service.
513    *
514    * @return \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface
515    *   The stream wrapper manager service
516    *
517    * @todo Properly inject this service in Drupal 9.0.x.
518    */
519   protected function getStreamWrapperManager() {
520     return \Drupal::service('stream_wrapper_manager');
521   }
522
523 }