Upgraded drupal core with security updates
[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 image was flushed after updating the style.
207     // This is especially important when renaming the style. Make sure that
208     // the old image directory has been deleted.
209     $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()]));
210
211     // Load the style by the new name with the new weights.
212     $style = ImageStyle::load($style_name);
213
214     // Confirm the new style order was saved.
215     $effect_edits_order = array_reverse($effect_edits_order);
216     $order_correct = TRUE;
217     $index = 0;
218     foreach ($style->getEffects() as $effect) {
219       if ($effect_edits_order[$index] != $effect->getPluginId()) {
220         $order_correct = FALSE;
221       }
222       $index++;
223     }
224     $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
225
226     // Image effect deletion form.
227
228     // Create an image to make sure it gets flushed after deleting an effect.
229     $image_path = $this->createSampleImage($style);
230     $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));
231
232     // Delete the 'image_crop' effect from the style.
233     $this->drupalPostForm($style_path . '/effects/' . $uuids['image_crop'] . '/delete', [], t('Delete'));
234     // Confirm that the form submission was successful.
235     $this->assertResponse(200);
236     $image_crop_effect = $style->getEffect($uuids['image_crop']);
237     $this->assertRaw(t('The image effect %name has been deleted.', ['%name' => $image_crop_effect->label()]));
238     // Confirm that there is no longer a link to the effect.
239     $this->assertNoLinkByHref($style_path . '/effects/' . $uuids['image_crop'] . '/delete');
240     // Refresh the image style information and verify that the effect was
241     // actually deleted.
242     $entity_type_manager = $this->container->get('entity_type.manager');
243     $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style->id());
244     $this->assertFalse($style->getEffects()->has($uuids['image_crop']), format_string(
245       'Effect with ID %uuid no longer found on image style %style',
246       [
247         '%uuid' => $uuids['image_crop'],
248         '%style' => $style->label(),
249       ]));
250
251     // Additional test on Rotate effect, for transparent background.
252     $edit = [
253       'data[degrees]' => 5,
254       'data[random]' => 0,
255       'data[bgcolor]' => '',
256     ];
257     $this->drupalPostForm($style_path, ['new' => 'image_rotate'], t('Add'));
258     $this->drupalPostForm(NULL, $edit, t('Add effect'));
259     $entity_type_manager = $this->container->get('entity_type.manager');
260     $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style_name);
261     $this->assertEqual(count($style->getEffects()), 6, 'Rotate effect with transparent background was added.');
262
263     // Style deletion form.
264
265     // Delete the style.
266     $this->drupalPostForm($style_path . '/delete', [], t('Delete'));
267
268     // Confirm the style directory has been removed.
269     $directory = file_default_scheme() . '://styles/' . $style_name;
270     $this->assertFalse(is_dir($directory), format_string('Image style %style directory removed on style deletion.', ['%style' => $style->label()]));
271
272     $this->assertFalse(ImageStyle::load($style_name), format_string('Image style %style successfully deleted.', ['%style' => $style->label()]));
273
274     // Test empty text when there are no image styles.
275
276     // Delete all image styles.
277     foreach (ImageStyle::loadMultiple() as $image_style) {
278       $image_style->delete();
279     }
280
281     // Confirm that the empty text is correct on the image styles page.
282     $this->drupalGet($admin_path);
283     $this->assertRaw(t('There are currently no styles. <a href=":url">Add a new one</a>.', [
284       ':url' => \Drupal::url('image.style_add'),
285     ]));
286
287   }
288
289   /**
290    * Tests editing Ajax-enabled image effect forms.
291    */
292   public function testAjaxEnabledEffectForm() {
293     $admin_path = 'admin/config/media/image-styles';
294
295     // Setup a style to be created and effects to add to it.
296     $style_name = strtolower($this->randomMachineName(10));
297     $style_label = $this->randomString();
298     $style_path = $admin_path . '/manage/' . $style_name;
299     $effect_edit = [
300       'data[test_parameter]' => 100,
301     ];
302
303     // Add style form.
304     $edit = [
305       'name' => $style_name,
306       'label' => $style_label,
307     ];
308     $this->drupalPostForm($admin_path . '/add', $edit, t('Create new style'));
309     $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
310
311     // Add two Ajax-enabled test effects.
312     $this->drupalPostForm($style_path, ['new' => 'image_module_test_ajax'], t('Add'));
313     $this->drupalPostForm(NULL, $effect_edit, t('Add effect'));
314     $this->drupalPostForm($style_path, ['new' => 'image_module_test_ajax'], t('Add'));
315     $this->drupalPostForm(NULL, $effect_edit, t('Add effect'));
316
317     // Load the saved image style.
318     $style = ImageStyle::load($style_name);
319
320     // Edit back the effects.
321     foreach ($style->getEffects() as $uuid => $effect) {
322       $effect_path = $admin_path . '/manage/' . $style_name . '/effects/' . $uuid;
323       $this->drupalGet($effect_path);
324       $this->drupalPostAjaxForm(NULL, $effect_edit, ['op' => t('Ajax refresh')]);
325       $this->drupalPostForm(NULL, $effect_edit, t('Update effect'));
326     }
327
328   }
329
330   /**
331    * Test deleting a style and choosing a replacement style.
332    */
333   public function testStyleReplacement() {
334     // Create a new style.
335     $style_name = strtolower($this->randomMachineName(10));
336     $style_label = $this->randomString();
337     $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
338     $style->save();
339     $style_path = 'admin/config/media/image-styles/manage/';
340
341     // Create an image field that uses the new style.
342     $field_name = strtolower($this->randomMachineName(10));
343     $this->createImageField($field_name, 'article');
344     entity_get_display('node', 'article', 'default')
345       ->setComponent($field_name, [
346         'type' => 'image',
347         'settings' => ['image_style' => $style_name],
348       ])
349       ->save();
350
351     // Create a new node with an image attached.
352     $test_image = current($this->drupalGetTestFiles('image'));
353     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
354     $node = Node::load($nid);
355
356     // Get node field original image URI.
357     $fid = $node->get($field_name)->target_id;
358     $original_uri = File::load($fid)->getFileUri();
359
360     // Test that image is displayed using newly created style.
361     $this->drupalGet('node/' . $nid);
362     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
363
364     // Rename the style and make sure the image field is updated.
365     $new_style_name = strtolower($this->randomMachineName(10));
366     $new_style_label = $this->randomString();
367     $edit = [
368       'name' => $new_style_name,
369       'label' => $new_style_label,
370     ];
371     $this->drupalPostForm($style_path . $style_name, $edit, t('Update style'));
372     $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]));
373     $this->drupalGet('node/' . $nid);
374
375     // Reload the image style using the new name.
376     $style = ImageStyle::load($new_style_name);
377     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
378
379     // Delete the style and choose a replacement style.
380     $edit = [
381       'replacement' => 'thumbnail',
382     ];
383     $this->drupalPostForm($style_path . $new_style_name . '/delete', $edit, t('Delete'));
384     $message = t('The image style %name has been deleted.', ['%name' => $new_style_label]);
385     $this->assertRaw($message);
386
387     $replacement_style = ImageStyle::load('thumbnail');
388     $this->drupalGet('node/' . $nid);
389     $this->assertRaw(file_url_transform_relative($replacement_style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
390   }
391
392   /**
393    * Verifies that editing an image effect does not cause it to be duplicated.
394    */
395   public function testEditEffect() {
396     // Add a scale effect.
397     $style_name = 'test_style_effect_edit';
398     $this->drupalGet('admin/config/media/image-styles/add');
399     $this->drupalPostForm(NULL, ['label' => 'Test style effect edit', 'name' => $style_name], t('Create new style'));
400     $this->drupalPostForm(NULL, ['new' => 'image_scale_and_crop'], t('Add'));
401     $this->drupalPostForm(NULL, ['data[width]' => '300', 'data[height]' => '200'], t('Add effect'));
402     $this->assertText(t('Scale and crop 300×200'));
403
404     // There should normally be only one edit link on this page initially.
405     $this->clickLink(t('Edit'));
406     $this->drupalPostForm(NULL, ['data[width]' => '360', 'data[height]' => '240'], t('Update effect'));
407     $this->assertText(t('Scale and crop 360×240'));
408
409     // Check that the previous effect is replaced.
410     $this->assertNoText(t('Scale and crop 300×200'));
411
412     // Add another scale effect.
413     $this->drupalGet('admin/config/media/image-styles/add');
414     $this->drupalPostForm(NULL, ['label' => 'Test style scale edit scale', 'name' => 'test_style_scale_edit_scale'], t('Create new style'));
415     $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
416     $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
417
418     // Edit the scale effect that was just added.
419     $this->clickLink(t('Edit'));
420     $this->drupalPostForm(NULL, ['data[width]' => '24', 'data[height]' => '19'], t('Update effect'));
421     $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
422
423     // Add another scale effect and make sure both exist.
424     $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
425     $this->assertText(t('Scale 24×19'));
426     $this->assertText(t('Scale 12×19'));
427
428     // Try to edit a nonexistent effect.
429     $uuid = $this->container->get('uuid');
430     $this->drupalGet('admin/config/media/image-styles/manage/' . $style_name . '/effects/' . $uuid->generate());
431     $this->assertResponse(404);
432   }
433
434   /**
435    * Test flush user interface.
436    */
437   public function testFlushUserInterface() {
438     $admin_path = 'admin/config/media/image-styles';
439
440     // Create a new style.
441     $style_name = strtolower($this->randomMachineName(10));
442     $style = ImageStyle::create(['name' => $style_name, 'label' => $this->randomString()]);
443     $style->save();
444
445     // Create an image to make sure it gets flushed.
446     $files = $this->drupalGetTestFiles('image');
447     $image_uri = $files[0]->uri;
448     $derivative_uri = $style->buildUri($image_uri);
449     $this->assertTrue($style->createDerivative($image_uri, $derivative_uri));
450     $this->assertEqual($this->getImageCount($style), 1);
451
452     // Go to image styles list page and check if the flush operation link
453     // exists.
454     $this->drupalGet($admin_path);
455     $flush_path = $admin_path . '/manage/' . $style_name . '/flush';
456     $this->assertLinkByHref($flush_path);
457
458     // Flush the image style derivatives using the user interface.
459     $this->drupalPostForm($flush_path, [], t('Flush'));
460
461     // The derivative image file should have been deleted.
462     $this->assertEqual($this->getImageCount($style), 0);
463   }
464
465   /**
466    * Tests image style configuration import that does a delete.
467    */
468   public function testConfigImport() {
469     // Create a new style.
470     $style_name = strtolower($this->randomMachineName(10));
471     $style_label = $this->randomString();
472     $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
473     $style->save();
474
475     // Create an image field that uses the new style.
476     $field_name = strtolower($this->randomMachineName(10));
477     $this->createImageField($field_name, 'article');
478     entity_get_display('node', 'article', 'default')
479       ->setComponent($field_name, [
480         'type' => 'image',
481         'settings' => ['image_style' => $style_name],
482       ])
483       ->save();
484
485     // Create a new node with an image attached.
486     $test_image = current($this->drupalGetTestFiles('image'));
487     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
488     $node = Node::load($nid);
489
490     // Get node field original image URI.
491     $fid = $node->get($field_name)->target_id;
492     $original_uri = File::load($fid)->getFileUri();
493
494     // Test that image is displayed using newly created style.
495     $this->drupalGet('node/' . $nid);
496     $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
497
498     // Copy config to sync, and delete the image style.
499     $sync = $this->container->get('config.storage.sync');
500     $active = $this->container->get('config.storage');
501     // Remove the image field from the display, to avoid a dependency error
502     // during import.
503     EntityViewDisplay::load('node.article.default')
504       ->removeComponent($field_name)
505       ->save();
506     $this->copyConfig($active, $sync);
507     $sync->delete('image.style.' . $style_name);
508     $this->configImporter()->import();
509
510     $this->assertFalse(ImageStyle::load($style_name), 'Style deleted after config import.');
511     $this->assertEqual($this->getImageCount($style), 0, 'Image style was flushed after being deleted by config import.');
512   }
513
514   /**
515    * Tests access for the image style listing.
516    */
517   public function testImageStyleAccess() {
518     $style = ImageStyle::create(['name' => 'style_foo', 'label' => $this->randomString()]);
519     $style->save();
520
521     $this->drupalGet('admin/config/media/image-styles');
522     $this->clickLink(t('Edit'));
523     $this->assertRaw(t('Select a new effect'));
524   }
525
526 }