Security update for Core, with self-updated composer
[yaffs-website] / web / core / modules / image / src / Tests / ImageAdminStylesTest.php
1 <?php
2
3 namespace Drupal\image\Tests;
4
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\Core\Entity\Entity\EntityViewDisplay;
7 use Drupal\image\Entity\ImageStyle;
8 use Drupal\image\ImageStyleInterface;
9 use Drupal\node\Entity\Node;
10 use Drupal\file\Entity\File;
11
12 /**
13  * Tests creation, deletion, and editing of image styles and effects.
14  *
15  * @group image
16  */
17 class ImageAdminStylesTest extends ImageFieldTestBase {
18
19   /**
20    * Given an image style, generate an image.
21    */
22   public function createSampleImage(ImageStyleInterface $style) {
23     static $file_path;
24
25     // First, we need to make sure we have an image in our testing
26     // file directory. Copy over an image on the first run.
27     if (!isset($file_path)) {
28       $files = $this->drupalGetTestFiles('image');
29       $file = reset($files);
30       $file_path = file_unmanaged_copy($file->uri);
31     }
32
33     return $style->buildUrl($file_path) ? $file_path : FALSE;
34   }
35
36   /**
37    * Count the number of images currently create for a style.
38    */
39   public function getImageCount(ImageStyleInterface $style) {
40     return count(file_scan_directory('public://styles/' . $style->id(), '/.*/'));
41   }
42
43   /**
44    * Test creating an image style with a numeric name and ensuring it can be
45    * applied to an image.
46    */
47   public function testNumericStyleName() {
48     $style_name = rand();
49     $style_label = $this->randomString();
50     $edit = [
51       'name' => $style_name,
52       'label' => $style_label,
53     ];
54     $this->drupalPostForm('admin/config/media/image-styles/add', $edit, t('Create new style'));
55     $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
56     $options = image_style_options();
57     $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', ['%key' => $style_name]));
58   }
59
60   /**
61    * General test to add a style, add/remove/edit effects to it, then delete it.
62    */
63   public function testStyle() {
64     $admin_path = 'admin/config/media/image-styles';
65
66     // Setup a style to be created and effects to add to it.
67     $style_name = strtolower($this->randomMachineName(10));
68     $style_label = $this->randomString();
69     $style_path = $admin_path . '/manage/' . $style_name;
70     $effect_edits = [
71       'image_resize' => [
72         'width' => 100,
73         'height' => 101,
74       ],
75       'image_scale' => [
76         'width' => 110,
77         'height' => 111,
78         'upscale' => 1,
79       ],
80       'image_scale_and_crop' => [
81         'width' => 120,
82         'height' => 121,
83       ],
84       'image_crop' => [
85         'width' => 130,
86         'height' => 131,
87         'anchor' => 'left-top',
88       ],
89       'image_desaturate' => [
90         // No options for desaturate.
91       ],
92       'image_rotate' => [
93         'degrees' => 5,
94         'random' => 1,
95         'bgcolor' => '#FFFF00',
96       ],
97     ];
98
99     // Add style form.
100
101     $edit = [
102       'name' => $style_name,
103       'label' => $style_label,
104     ];
105     $this->drupalPostForm($admin_path . '/add', $edit, t('Create new style'));
106     $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
107
108     // Ensure that the expected entity operations are there.
109     $this->drupalGet($admin_path);
110     $this->assertLinkByHref($style_path);
111     $this->assertLinkByHref($style_path . '/flush');
112     $this->assertLinkByHref($style_path . '/delete');
113
114     // Add effect form.
115
116     // Add each sample effect to the style.
117     foreach ($effect_edits as $effect => $edit) {
118       $edit_data = [];
119       foreach ($edit as $field => $value) {
120         $edit_data['data[' . $field . ']'] = $value;
121       }
122       // Add the effect.
123       $this->drupalPostForm($style_path, ['new' => $effect], t('Add'));
124       if (!empty($edit)) {
125         $this->drupalPostForm(NULL, $edit_data, t('Add effect'));
126       }
127     }
128
129     // Load the saved image style.
130     $style = ImageStyle::load($style_name);
131
132     // Ensure that third party settings were added to the config entity.
133     // These are added by a hook_image_style_presave() implemented in
134     // image_module_test module.
135     $this->assertEqual('bar', $style->getThirdPartySetting('image_module_test', 'foo'), 'Third party settings were added to the image style.');
136
137     // Ensure that the image style URI matches our expected path.
138     $style_uri_path = $style->url();
139     $this->assertTrue(strpos($style_uri_path, $style_path) !== FALSE, 'The image style URI is correct.');
140
141     // Confirm that all effects on the image style have settings that match
142     // what was saved.
143     $uuids = [];
144     foreach ($style->getEffects() as $uuid => $effect) {
145       // Store the uuid for later use.
146       $uuids[$effect->getPluginId()] = $uuid;
147       $effect_configuration = $effect->getConfiguration();
148       foreach ($effect_edits[$effect->getPluginId()] as $field => $value) {
149         $this->assertEqual($value, $effect_configuration['data'][$field], SafeMarkup::format('The %field field in the %effect effect has the correct value of %value.', ['%field' => $field, '%effect' => $effect->getPluginId(), '%value' => $value]));
150       }
151     }
152
153     // Assert that every effect was saved.
154     foreach (array_keys($effect_edits) as $effect_name) {
155       $this->assertTrue(isset($uuids[$effect_name]), format_string(
156         'A %effect_name effect was saved with ID %uuid',
157         [
158           '%effect_name' => $effect_name,
159           '%uuid' => $uuids[$effect_name],
160         ]));
161     }
162
163     // Image style overview form (ordering and renaming).
164
165     // Confirm the order of effects is maintained according to the order we
166     // added the fields.
167     $effect_edits_order = array_keys($effect_edits);
168     $order_correct = TRUE;
169     $index = 0;
170     foreach ($style->getEffects() as $effect) {
171       if ($effect_edits_order[$index] != $effect->getPluginId()) {
172         $order_correct = FALSE;
173       }
174       $index++;
175     }
176     $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
177
178     // Test the style overview form.
179     // Change the name of the style and adjust the weights of effects.
180     $style_name = strtolower($this->randomMachineName(10));
181     $style_label = $this->randomMachineName();
182     $weight = count($effect_edits);
183     $edit = [
184       'name' => $style_name,
185       'label' => $style_label,
186     ];
187     foreach ($style->getEffects() as $uuid => $effect) {
188       $edit['effects[' . $uuid . '][weight]'] = $weight;
189       $weight--;
190     }
191
192     // Create an image to make sure it gets flushed after saving.
193     $image_path = $this->createSampleImage($style);
194     $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));
195
196     $this->drupalPostForm($style_path, $edit, t('Update style'));
197
198     // Note that after changing the style name, the style path is changed.
199     $style_path = 'admin/config/media/image-styles/manage/' . $style_name;
200
201     // Check that the URL was updated.
202     $this->drupalGet($style_path);
203     $this->assertTitle(t('Edit style @name | Drupal', ['@name' => $style_label]));
204     $this->assertResponse(200, format_string('Image style %original renamed to %new', ['%original' => $style->id(), '%new' => $style_name]));
205
206     // Check that the available image effects are properly sorted.
207     $option = $this->xpath('//select[@id=:id]//option', [':id' => 'edit-new--2']);
208     $this->assertTrue($option[1] == 'Ajax test', '"Ajax test" is the first selectable effect.');
209
210     // Check that the image was flushed after updating the style.
211     // This is especially important when renaming the style. Make sure that
212     // the old image directory has been deleted.
213     $this->assertEqual($this->getImageCount($style), 0, format_string('Image style %style was flushed after renaming the style and updating the order of effects.', ['%style' => $style->label()]));
214
215     // Load the style by the new name with the new weights.
216     $style = ImageStyle::load($style_name);
217
218     // Confirm the new style order was saved.
219     $effect_edits_order = array_reverse($effect_edits_order);
220     $order_correct = TRUE;
221     $index = 0;
222     foreach ($style->getEffects() as $effect) {
223       if ($effect_edits_order[$index] != $effect->getPluginId()) {
224         $order_correct = FALSE;
225       }
226       $index++;
227     }
228     $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
229
230     // Image effect deletion form.
231
232     // Create an image to make sure it gets flushed after deleting an effect.
233     $image_path = $this->createSampleImage($style);
234     $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));
235
236     // Delete the 'image_crop' effect from the style.
237     $this->drupalPostForm($style_path . '/effects/' . $uuids['image_crop'] . '/delete', [], t('Delete'));
238     // Confirm that the form submission was successful.
239     $this->assertResponse(200);
240     $image_crop_effect = $style->getEffect($uuids['image_crop']);
241     $this->assertRaw(t('The image effect %name has been deleted.', ['%name' => $image_crop_effect->label()]));
242     // Confirm that there is no longer a link to the effect.
243     $this->assertNoLinkByHref($style_path . '/effects/' . $uuids['image_crop'] . '/delete');
244     // Refresh the image style information and verify that the effect was
245     // actually deleted.
246     $entity_type_manager = $this->container->get('entity_type.manager');
247     $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style->id());
248     $this->assertFalse($style->getEffects()->has($uuids['image_crop']), format_string(
249       'Effect with ID %uuid no longer found on image style %style',
250       [
251         '%uuid' => $uuids['image_crop'],
252         '%style' => $style->label(),
253       ]));
254
255     // Additional test on Rotate effect, for transparent background.
256     $edit = [
257       'data[degrees]' => 5,
258       'data[random]' => 0,
259       'data[bgcolor]' => '',
260     ];
261     $this->drupalPostForm($style_path, ['new' => 'image_rotate'], t('Add'));
262     $this->drupalPostForm(NULL, $edit, t('Add effect'));
263     $entity_type_manager = $this->container->get('entity_type.manager');
264     $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style_name);
265     $this->assertEqual(count($style->getEffects()), 6, 'Rotate effect with transparent background was added.');
266
267     // Style deletion form.
268
269     // Delete the style.
270     $this->drupalPostForm($style_path . '/delete', [], t('Delete'));
271
272     // Confirm the style directory has been removed.
273     $directory = file_default_scheme() . '://styles/' . $style_name;
274     $this->assertFalse(is_dir($directory), format_string('Image style %style directory removed on style deletion.', ['%style' => $style->label()]));
275
276     $this->assertFalse(ImageStyle::load($style_name), format_string('Image style %style successfully deleted.', ['%style' => $style->label()]));
277
278     // Test empty text when there are no image styles.
279
280     // Delete all image styles.
281     foreach (ImageStyle::loadMultiple() as $image_style) {
282       $image_style->delete();
283     }
284
285     // Confirm that the empty text is correct on the image styles page.
286     $this->drupalGet($admin_path);
287     $this->assertRaw(t('There are currently no styles. <a href=":url">Add a new one</a>.', [
288       ':url' => \Drupal::url('image.style_add'),
289     ]));
290
291   }
292
293   /**
294    * Tests editing Ajax-enabled image effect forms.
295    */
296   public function testAjaxEnabledEffectForm() {
297     $admin_path = 'admin/config/media/image-styles';
298
299     // Setup a style to be created and effects to add to it.
300     $style_name = strtolower($this->randomMachineName(10));
301     $style_label = $this->randomString();
302     $style_path = $admin_path . '/manage/' . $style_name;
303     $effect_edit = [
304       'data[test_parameter]' => 100,
305     ];
306
307     // Add style form.
308     $edit = [
309       'name' => $style_name,
310       'label' => $style_label,
311     ];
312     $this->drupalPostForm($admin_path . '/add', $edit, t('Create new style'));
313     $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
314
315     // Add two Ajax-enabled test effects.
316     $this->drupalPostForm($style_path, ['new' => 'image_module_test_ajax'], t('Add'));
317     $this->drupalPostForm(NULL, $effect_edit, t('Add effect'));
318     $this->drupalPostForm($style_path, ['new' => 'image_module_test_ajax'], t('Add'));
319     $this->drupalPostForm(NULL, $effect_edit, t('Add effect'));
320
321     // Load the saved image style.
322     $style = ImageStyle::load($style_name);
323
324     // Edit back the effects.
325     foreach ($style->getEffects() as $uuid => $effect) {
326       $effect_path = $admin_path . '/manage/' . $style_name . '/effects/' . $uuid;
327       $this->drupalGet($effect_path);
328       $this->drupalPostAjaxForm(NULL, $effect_edit, ['op' => t('Ajax refresh')]);
329       $this->drupalPostForm(NULL, $effect_edit, t('Update effect'));
330     }
331
332   }
333
334   /**
335    * Test deleting a style and choosing a replacement style.
336    */
337   public function testStyleReplacement() {
338     // Create a new style.
339     $style_name = strtolower($this->randomMachineName(10));
340     $style_label = $this->randomString();
341     $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
342     $style->save();
343     $style_path = 'admin/config/media/image-styles/manage/';
344
345     // Create an image field that uses the new style.
346     $field_name = strtolower($this->randomMachineName(10));
347     $this->createImageField($field_name, 'article');
348     entity_get_display('node', 'article', 'default')
349       ->setComponent($field_name, [
350         'type' => 'image',
351         'settings' => ['image_style' => $style_name],
352       ])
353       ->save();
354
355     // Create a new node with an image attached.
356     $test_image = current($this->drupalGetTestFiles('image'));
357     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
358     $node = Node::load($nid);
359
360     // Get node field original image URI.
361     $fid = $node->get($field_name)->target_id;
362     $original_uri = File::load($fid)->getFileUri();
363
364     // Test that image is displayed using newly created style.
365     $this->drupalGet('node/' . $nid);
366     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
367
368     // Rename the style and make sure the image field is updated.
369     $new_style_name = strtolower($this->randomMachineName(10));
370     $new_style_label = $this->randomString();
371     $edit = [
372       'name' => $new_style_name,
373       'label' => $new_style_label,
374     ];
375     $this->drupalPostForm($style_path . $style_name, $edit, t('Update style'));
376     $this->assertText(t('Changes to the style have been saved.'), format_string('Style %name was renamed to %new_name.', ['%name' => $style_name, '%new_name' => $new_style_name]));
377     $this->drupalGet('node/' . $nid);
378
379     // Reload the image style using the new name.
380     $style = ImageStyle::load($new_style_name);
381     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
382
383     // Delete the style and choose a replacement style.
384     $edit = [
385       'replacement' => 'thumbnail',
386     ];
387     $this->drupalPostForm($style_path . $new_style_name . '/delete', $edit, t('Delete'));
388     $message = t('The image style %name has been deleted.', ['%name' => $new_style_label]);
389     $this->assertRaw($message);
390
391     $replacement_style = ImageStyle::load('thumbnail');
392     $this->drupalGet('node/' . $nid);
393     $this->assertRaw(file_url_transform_relative($replacement_style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
394   }
395
396   /**
397    * Verifies that editing an image effect does not cause it to be duplicated.
398    */
399   public function testEditEffect() {
400     // Add a scale effect.
401     $style_name = 'test_style_effect_edit';
402     $this->drupalGet('admin/config/media/image-styles/add');
403     $this->drupalPostForm(NULL, ['label' => 'Test style effect edit', 'name' => $style_name], t('Create new style'));
404     $this->drupalPostForm(NULL, ['new' => 'image_scale_and_crop'], t('Add'));
405     $this->drupalPostForm(NULL, ['data[width]' => '300', 'data[height]' => '200'], t('Add effect'));
406     $this->assertText(t('Scale and crop 300×200'));
407
408     // There should normally be only one edit link on this page initially.
409     $this->clickLink(t('Edit'));
410     $this->drupalPostForm(NULL, ['data[width]' => '360', 'data[height]' => '240'], t('Update effect'));
411     $this->assertText(t('Scale and crop 360×240'));
412
413     // Check that the previous effect is replaced.
414     $this->assertNoText(t('Scale and crop 300×200'));
415
416     // Add another scale effect.
417     $this->drupalGet('admin/config/media/image-styles/add');
418     $this->drupalPostForm(NULL, ['label' => 'Test style scale edit scale', 'name' => 'test_style_scale_edit_scale'], t('Create new style'));
419     $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
420     $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
421
422     // Edit the scale effect that was just added.
423     $this->clickLink(t('Edit'));
424     $this->drupalPostForm(NULL, ['data[width]' => '24', 'data[height]' => '19'], t('Update effect'));
425     $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
426
427     // Add another scale effect and make sure both exist.
428     $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
429     $this->assertText(t('Scale 24×19'));
430     $this->assertText(t('Scale 12×19'));
431
432     // Try to edit a nonexistent effect.
433     $uuid = $this->container->get('uuid');
434     $this->drupalGet('admin/config/media/image-styles/manage/' . $style_name . '/effects/' . $uuid->generate());
435     $this->assertResponse(404);
436   }
437
438   /**
439    * Test flush user interface.
440    */
441   public function testFlushUserInterface() {
442     $admin_path = 'admin/config/media/image-styles';
443
444     // Create a new style.
445     $style_name = strtolower($this->randomMachineName(10));
446     $style = ImageStyle::create(['name' => $style_name, 'label' => $this->randomString()]);
447     $style->save();
448
449     // Create an image to make sure it gets flushed.
450     $files = $this->drupalGetTestFiles('image');
451     $image_uri = $files[0]->uri;
452     $derivative_uri = $style->buildUri($image_uri);
453     $this->assertTrue($style->createDerivative($image_uri, $derivative_uri));
454     $this->assertEqual($this->getImageCount($style), 1);
455
456     // Go to image styles list page and check if the flush operation link
457     // exists.
458     $this->drupalGet($admin_path);
459     $flush_path = $admin_path . '/manage/' . $style_name . '/flush';
460     $this->assertLinkByHref($flush_path);
461
462     // Flush the image style derivatives using the user interface.
463     $this->drupalPostForm($flush_path, [], t('Flush'));
464
465     // The derivative image file should have been deleted.
466     $this->assertEqual($this->getImageCount($style), 0);
467   }
468
469   /**
470    * Tests image style configuration import that does a delete.
471    */
472   public function testConfigImport() {
473     // Create a new style.
474     $style_name = strtolower($this->randomMachineName(10));
475     $style_label = $this->randomString();
476     $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
477     $style->save();
478
479     // Create an image field that uses the new style.
480     $field_name = strtolower($this->randomMachineName(10));
481     $this->createImageField($field_name, 'article');
482     entity_get_display('node', 'article', 'default')
483       ->setComponent($field_name, [
484         'type' => 'image',
485         'settings' => ['image_style' => $style_name],
486       ])
487       ->save();
488
489     // Create a new node with an image attached.
490     $test_image = current($this->drupalGetTestFiles('image'));
491     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
492     $node = Node::load($nid);
493
494     // Get node field original image URI.
495     $fid = $node->get($field_name)->target_id;
496     $original_uri = File::load($fid)->getFileUri();
497
498     // Test that image is displayed using newly created style.
499     $this->drupalGet('node/' . $nid);
500     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
501
502     // Copy config to sync, and delete the image style.
503     $sync = $this->container->get('config.storage.sync');
504     $active = $this->container->get('config.storage');
505     // Remove the image field from the display, to avoid a dependency error
506     // during import.
507     EntityViewDisplay::load('node.article.default')
508       ->removeComponent($field_name)
509       ->save();
510     $this->copyConfig($active, $sync);
511     $sync->delete('image.style.' . $style_name);
512     $this->configImporter()->import();
513
514     $this->assertFalse(ImageStyle::load($style_name), 'Style deleted after config import.');
515     $this->assertEqual($this->getImageCount($style), 0, 'Image style was flushed after being deleted by config import.');
516   }
517
518   /**
519    * Tests access for the image style listing.
520    */
521   public function testImageStyleAccess() {
522     $style = ImageStyle::create(['name' => 'style_foo', 'label' => $this->randomString()]);
523     $style->save();
524
525     $this->drupalGet('admin/config/media/image-styles');
526     $this->clickLink(t('Edit'));
527     $this->assertRaw(t('Select a new effect'));
528   }
529
530 }