9c105c1434f979ea24d2ff297c39d497d2188675
[yaffs-website] / web / core / modules / image / src / Tests / ImageFieldDisplayTest.php
1 <?php
2
3 namespace Drupal\image\Tests;
4
5 use Drupal\Core\Field\FieldStorageDefinitionInterface;
6 use Drupal\field\Entity\FieldStorageConfig;
7 use Drupal\user\RoleInterface;
8 use Drupal\image\Entity\ImageStyle;
9
10 /**
11  * Tests the display of image fields.
12  *
13  * @group image
14  */
15 class ImageFieldDisplayTest extends ImageFieldTestBase {
16
17   protected $dumpHeaders = TRUE;
18
19   /**
20    * Modules to enable.
21    *
22    * @var array
23    */
24   public static $modules = ['field_ui'];
25
26   /**
27    * Test image formatters on node display for public files.
28    */
29   public function testImageFieldFormattersPublic() {
30     $this->_testImageFieldFormatters('public');
31   }
32
33   /**
34    * Test image formatters on node display for private files.
35    */
36   public function testImageFieldFormattersPrivate() {
37     // Remove access content permission from anonymous users.
38     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, ['access content' => FALSE]);
39     $this->_testImageFieldFormatters('private');
40   }
41
42   /**
43    * Test image formatters on node display.
44    */
45   public function _testImageFieldFormatters($scheme) {
46     /** @var \Drupal\Core\Render\RendererInterface $renderer */
47     $renderer = $this->container->get('renderer');
48     $node_storage = $this->container->get('entity.manager')->getStorage('node');
49     $field_name = strtolower($this->randomMachineName());
50     $field_settings = ['alt_field_required' => 0];
51     $instance = $this->createImageField($field_name, 'article', ['uri_scheme' => $scheme], $field_settings);
52
53     // Go to manage display page.
54     $this->drupalGet("admin/structure/types/manage/article/display");
55
56     // Test for existence of link to image styles configuration.
57     $this->drupalPostAjaxForm(NULL, [], "{$field_name}_settings_edit");
58     $this->assertLinkByHref(\Drupal::url('entity.image_style.collection'), 0, 'Link to image styles configuration is found');
59
60     // Remove 'administer image styles' permission from testing admin user.
61     $admin_user_roles = $this->adminUser->getRoles(TRUE);
62     user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => FALSE]);
63
64     // Go to manage display page again.
65     $this->drupalGet("admin/structure/types/manage/article/display");
66
67     // Test for absence of link to image styles configuration.
68     $this->drupalPostAjaxForm(NULL, [], "{$field_name}_settings_edit");
69     $this->assertNoLinkByHref(\Drupal::url('entity.image_style.collection'), 'Link to image styles configuration is absent when permissions are insufficient');
70
71     // Restore 'administer image styles' permission to testing admin user
72     user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
73
74     // Create a new node with an image attached.
75     $test_image = current($this->drupalGetTestFiles('image'));
76
77     // Ensure that preview works.
78     $this->previewNodeImage($test_image, $field_name, 'article');
79
80     // After previewing, make the alt field required. It cannot be required
81     // during preview because the form validation will fail.
82     $instance->setSetting('alt_field_required', 1);
83     $instance->save();
84
85     // Create alt text for the image.
86     $alt = $this->randomMachineName();
87
88     // Save node.
89     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
90     $node_storage->resetCache([$nid]);
91     $node = $node_storage->load($nid);
92
93     // Test that the default formatter is being used.
94     $file = $node->{$field_name}->entity;
95     $image_uri = $file->getFileUri();
96     $image = [
97       '#theme' => 'image',
98       '#uri' => $image_uri,
99       '#width' => 40,
100       '#height' => 20,
101       '#alt' => $alt,
102     ];
103     $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
104     $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
105
106     // Test the image linked to file formatter.
107     $display_options = [
108       'type' => 'image',
109       'settings' => ['image_link' => 'file'],
110     ];
111     $display = entity_get_display('node', $node->getType(), 'default');
112     $display->setComponent($field_name, $display_options)
113       ->save();
114
115     $image = [
116       '#theme' => 'image',
117       '#uri' => $image_uri,
118       '#width' => 40,
119       '#height' => 20,
120       '#alt' => $alt,
121     ];
122     $default_output = '<a href="' . file_create_url($image_uri) . '">' . $renderer->renderRoot($image) . '</a>';
123     $this->drupalGet('node/' . $nid);
124     $this->assertCacheTag($file->getCacheTags()[0]);
125     // @todo Remove in https://www.drupal.org/node/2646744.
126     $this->assertCacheContext('url.site');
127     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
128     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
129     $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
130     // Verify that the image can be downloaded.
131     $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
132     if ($scheme == 'private') {
133       // Only verify HTTP headers when using private scheme and the headers are
134       // sent by Drupal.
135       $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
136       $this->assertTrue(strstr($this->drupalGetHeader('Cache-Control'), 'private') !== FALSE, 'Cache-Control header was sent.');
137
138       // Log out and try to access the file.
139       $this->drupalLogout();
140       $this->drupalGet(file_create_url($image_uri));
141       $this->assertResponse('403', 'Access denied to original image as anonymous user.');
142
143       // Log in again.
144       $this->drupalLogin($this->adminUser);
145     }
146
147     // Test the image linked to content formatter.
148     $display_options['settings']['image_link'] = 'content';
149     $display->setComponent($field_name, $display_options)
150       ->save();
151     $image = [
152       '#theme' => 'image',
153       '#uri' => $image_uri,
154       '#width' => 40,
155       '#height' => 20,
156     ];
157     $this->drupalGet('node/' . $nid);
158     $this->assertCacheTag($file->getCacheTags()[0]);
159     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
160     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
161     $elements = $this->xpath(
162       '//a[@href=:path]/img[@src=:url and @alt=:alt and @width=:width and @height=:height]',
163       [
164         ':path' => $node->url(),
165         ':url' => file_url_transform_relative(file_create_url($image['#uri'])),
166         ':width' => $image['#width'],
167         ':height' => $image['#height'],
168         ':alt' => $alt,
169       ]
170     );
171     $this->assertEqual(count($elements), 1, 'Image linked to content formatter displaying correctly on full node view.');
172
173     // Test the image style 'thumbnail' formatter.
174     $display_options['settings']['image_link'] = '';
175     $display_options['settings']['image_style'] = 'thumbnail';
176     $display->setComponent($field_name, $display_options)
177       ->save();
178
179     // Ensure the derivative image is generated so we do not have to deal with
180     // image style callback paths.
181     $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
182     $image_style = [
183       '#theme' => 'image_style',
184       '#uri' => $image_uri,
185       '#width' => 40,
186       '#height' => 20,
187       '#style_name' => 'thumbnail',
188       '#alt' => $alt,
189     ];
190     $default_output = $renderer->renderRoot($image_style);
191     $this->drupalGet('node/' . $nid);
192     $image_style = ImageStyle::load('thumbnail');
193     $this->assertCacheTag($image_style->getCacheTags()[0]);
194     $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
195
196     if ($scheme == 'private') {
197       // Log out and try to access the file.
198       $this->drupalLogout();
199       $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
200       $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
201     }
202
203     // Test the image URL formatter without an image style.
204     $display_options = [
205       'type' => 'image_url',
206       'settings' => ['image_style' => ''],
207     ];
208     $expected_url = file_url_transform_relative(file_create_url($image_uri));
209     $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
210
211     // Test the image URL formatter with an image style.
212     $display_options['settings']['image_style'] = 'thumbnail';
213     $expected_url = file_url_transform_relative(ImageStyle::load('thumbnail')->buildUrl($image_uri));
214     $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
215   }
216
217   /**
218    * Tests for image field settings.
219    */
220   public function testImageFieldSettings() {
221     /** @var \Drupal\Core\Render\RendererInterface $renderer */
222     $renderer = $this->container->get('renderer');
223     $node_storage = $this->container->get('entity.manager')->getStorage('node');
224     $test_image = current($this->drupalGetTestFiles('image'));
225     list(, $test_image_extension) = explode('.', $test_image->filename);
226     $field_name = strtolower($this->randomMachineName());
227     $field_settings = [
228       'alt_field' => 1,
229       'file_extensions' => $test_image_extension,
230       'max_filesize' => '50 KB',
231       'max_resolution' => '100x100',
232       'min_resolution' => '10x10',
233       'title_field' => 1,
234     ];
235     $widget_settings = [
236       'preview_image_style' => 'medium',
237     ];
238     $field = $this->createImageField($field_name, 'article', [], $field_settings, $widget_settings);
239
240     // Verify that the min/max resolution set on the field are properly
241     // extracted, and displayed, on the image field's configuration form.
242     $this->drupalGet('admin/structure/types/manage/article/fields/' . $field->id());
243     $this->assertFieldByName('settings[max_resolution][x]', '100', 'Expected max resolution X value of 100.');
244     $this->assertFieldByName('settings[max_resolution][y]', '100', 'Expected max resolution Y value of 100.');
245     $this->assertFieldByName('settings[min_resolution][x]', '10', 'Expected min resolution X value of 10.');
246     $this->assertFieldByName('settings[min_resolution][y]', '10', 'Expected min resolution Y value of 10.');
247
248     $this->drupalGet('node/add/article');
249     $this->assertText(t('50 KB limit.'), 'Image widget max file size is displayed on article form.');
250     $this->assertText(t('Allowed types: @extensions.', ['@extensions' => $test_image_extension]), 'Image widget allowed file types displayed on article form.');
251     $this->assertText(t('Images must be larger than 10x10 pixels. Images larger than 100x100 pixels will be resized.'), 'Image widget allowed resolution displayed on article form.');
252
253     // We have to create the article first and then edit it because the alt
254     // and title fields do not display until the image has been attached.
255
256     // Create alt text for the image.
257     $alt = $this->randomMachineName();
258
259     $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
260     $this->drupalGet('node/' . $nid . '/edit');
261     $this->assertFieldByName($field_name . '[0][alt]', '', 'Alt field displayed on article form.');
262     $this->assertFieldByName($field_name . '[0][title]', '', 'Title field displayed on article form.');
263     // Verify that the attached image is being previewed using the 'medium'
264     // style.
265     $node_storage->resetCache([$nid]);
266     $node = $node_storage->load($nid);
267     $file = $node->{$field_name}->entity;
268
269     $url = file_url_transform_relative(file_create_url(ImageStyle::load('medium')->buildUrl($file->getFileUri())));
270     $this->assertTrue($this->cssSelect('img[width=40][height=20][class=image-style-medium][src="' . $url . '"]'));
271
272     // Add alt/title fields to the image and verify that they are displayed.
273     $image = [
274       '#theme' => 'image',
275       '#uri' => $file->getFileUri(),
276       '#alt' => $alt,
277       '#title' => $this->randomMachineName(),
278       '#width' => 40,
279       '#height' => 20,
280     ];
281     $edit = [
282       $field_name . '[0][alt]' => $image['#alt'],
283       $field_name . '[0][title]' => $image['#title'],
284     ];
285     $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
286     $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
287     $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
288
289     // Verify that alt/title longer than allowed results in a validation error.
290     $test_size = 2000;
291     $edit = [
292       $field_name . '[0][alt]' => $this->randomMachineName($test_size),
293       $field_name . '[0][title]' => $this->randomMachineName($test_size),
294     ];
295     $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
296     $schema = $field->getFieldStorageDefinition()->getSchema();
297     $this->assertRaw(t('Alternative text cannot be longer than %max characters but is currently %length characters long.', [
298       '%max' => $schema['columns']['alt']['length'],
299       '%length' => $test_size,
300     ]));
301     $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', [
302       '%max' => $schema['columns']['title']['length'],
303       '%length' => $test_size,
304     ]));
305
306     // Set cardinality to unlimited and add upload a second image.
307     // The image widget is extending on the file widget, but the image field
308     // type does not have the 'display_field' setting which is expected by
309     // the file widget. This resulted in notices before when cardinality is not
310     // 1, so we need to make sure the file widget prevents these notices by
311     // providing all settings, even if they are not used.
312     // @see FileWidget::formMultipleElements().
313     $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $field_name . '/storage', ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED], t('Save field settings'));
314     $edit = [
315       'files[' . $field_name . '_1][]' => drupal_realpath($test_image->uri),
316     ];
317     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
318     // Add the required alt text.
319     $this->drupalPostForm(NULL, [$field_name . '[1][alt]' => $alt], t('Save and keep published'));
320     $this->assertText(format_string('Article @title has been updated.', ['@title' => $node->getTitle()]));
321
322     // Assert ImageWidget::process() calls FieldWidget::process().
323     $this->drupalGet('node/' . $node->id() . '/edit');
324     $edit = [
325       'files[' . $field_name . '_2][]' => drupal_realpath($test_image->uri),
326     ];
327     $this->drupalPostAjaxForm(NULL, $edit, $field_name . '_2_upload_button');
328     $this->assertNoRaw('<input multiple type="file" id="edit-' . strtr($field_name, '_', '-') . '-2-upload" name="files[' . $field_name . '_2][]" size="22" class="js-form-file form-file">');
329     $this->assertRaw('<input multiple type="file" id="edit-' . strtr($field_name, '_', '-') . '-3-upload" name="files[' . $field_name . '_3][]" size="22" class="js-form-file form-file">');
330   }
331
332   /**
333    * Test use of a default image with an image field.
334    */
335   public function testImageFieldDefaultImage() {
336     /** @var \Drupal\Core\Render\RendererInterface $renderer */
337     $renderer = $this->container->get('renderer');
338
339     $node_storage = $this->container->get('entity.manager')->getStorage('node');
340     // Create a new image field.
341     $field_name = strtolower($this->randomMachineName());
342     $this->createImageField($field_name, 'article');
343
344     // Create a new node, with no images and verify that no images are
345     // displayed.
346     $node = $this->drupalCreateNode(['type' => 'article']);
347     $this->drupalGet('node/' . $node->id());
348     // Verify that no image is displayed on the page by checking for the class
349     // that would be used on the image field.
350     $this->assertNoPattern('<div class="(.*?)field--name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
351     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
352     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
353
354     // Add a default image to the public image field.
355     $images = $this->drupalGetTestFiles('image');
356     $alt = $this->randomString(512);
357     $title = $this->randomString(1024);
358     $edit = [
359       // Get the path of the 'image-test.png' file.
360       'files[settings_default_image_uuid]' => drupal_realpath($images[0]->uri),
361       'settings[default_image][alt]' => $alt,
362       'settings[default_image][title]' => $title,
363     ];
364     $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
365     // Clear field definition cache so the new default image is detected.
366     \Drupal::entityManager()->clearCachedFieldDefinitions();
367     $field_storage = FieldStorageConfig::loadByName('node', $field_name);
368     $default_image = $field_storage->getSetting('default_image');
369     $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
370     $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
371     $image = [
372       '#theme' => 'image',
373       '#uri' => $file->getFileUri(),
374       '#alt' => $alt,
375       '#title' => $title,
376       '#width' => 40,
377       '#height' => 20,
378     ];
379     $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
380     $this->drupalGet('node/' . $node->id());
381     $this->assertCacheTag($file->getCacheTags()[0]);
382     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
383     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
384     $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
385
386     // Create a node with an image attached and ensure that the default image
387     // is not displayed.
388
389     // Create alt text for the image.
390     $alt = $this->randomMachineName();
391
392     // Upload the 'image-test.gif' file.
393     $nid = $this->uploadNodeImage($images[2], $field_name, 'article', $alt);
394     $node_storage->resetCache([$nid]);
395     $node = $node_storage->load($nid);
396     $file = $node->{$field_name}->entity;
397     $image = [
398       '#theme' => 'image',
399       '#uri' => $file->getFileUri(),
400       '#width' => 40,
401       '#height' => 20,
402       '#alt' => $alt,
403     ];
404     $image_output = str_replace("\n", NULL, $renderer->renderRoot($image));
405     $this->drupalGet('node/' . $nid);
406     $this->assertCacheTag($file->getCacheTags()[0]);
407     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
408     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
409     $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
410     $this->assertRaw($image_output, 'User supplied image is displayed.');
411
412     // Remove default image from the field and make sure it is no longer used.
413     $edit = [
414       'settings[default_image][uuid][fids]' => 0,
415     ];
416     $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
417     // Clear field definition cache so the new default image is detected.
418     \Drupal::entityManager()->clearCachedFieldDefinitions();
419     $field_storage = FieldStorageConfig::loadByName('node', $field_name);
420     $default_image = $field_storage->getSetting('default_image');
421     $this->assertFalse($default_image['uuid'], 'Default image removed from field.');
422     // Create an image field that uses the private:// scheme and test that the
423     // default image works as expected.
424     $private_field_name = strtolower($this->randomMachineName());
425     $this->createImageField($private_field_name, 'article', ['uri_scheme' => 'private']);
426     // Add a default image to the new field.
427     $edit = [
428       // Get the path of the 'image-test.gif' file.
429       'files[settings_default_image_uuid]' => drupal_realpath($images[2]->uri),
430       'settings[default_image][alt]' => $alt,
431       'settings[default_image][title]' => $title,
432     ];
433     $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $private_field_name . '/storage', $edit, t('Save field settings'));
434     // Clear field definition cache so the new default image is detected.
435     \Drupal::entityManager()->clearCachedFieldDefinitions();
436
437     $private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
438     $default_image = $private_field_storage->getSetting('default_image');
439     $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
440     $this->assertEqual('private', file_uri_scheme($file->getFileUri()), 'Default image uses private:// scheme.');
441     $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
442     // Create a new node with no image attached and ensure that default private
443     // image is displayed.
444     $node = $this->drupalCreateNode(['type' => 'article']);
445     $image = [
446       '#theme' => 'image',
447       '#uri' => $file->getFileUri(),
448       '#alt' => $alt,
449       '#title' => $title,
450       '#width' => 40,
451       '#height' => 20,
452     ];
453     $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
454     $this->drupalGet('node/' . $node->id());
455     $this->assertCacheTag($file->getCacheTags()[0]);
456     $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
457     $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
458     $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');
459   }
460
461 }