ImageFieldDisplayTest.php 20.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\image\Tests\ImageFieldDisplayTest.
6 7 8 9
 */

namespace Drupal\image\Tests;

10
use Drupal\Core\Field\FieldStorageDefinitionInterface;
11
use Drupal\field\Entity\FieldStorageConfig;
12
use Drupal\user\RoleInterface;
13
use Drupal\image\Entity\ImageStyle;
14

15
/**
16 17 18
 * Tests the display of image fields.
 *
 * @group image
19 20
 */
class ImageFieldDisplayTest extends ImageFieldTestBase {
21

22 23
  protected $dumpHeaders = TRUE;

24 25 26 27 28 29 30
  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('field_ui');

31 32 33 34 35 36 37 38 39 40 41 42
  /**
   * Test image formatters on node display for public files.
   */
  function testImageFieldFormattersPublic() {
    $this->_testImageFieldFormatters('public');
  }

  /**
   * Test image formatters on node display for private files.
   */
  function testImageFieldFormattersPrivate() {
    // Remove access content permission from anonymous users.
43
    user_role_change_permissions(RoleInterface::ANONYMOUS_ID, array('access content' => FALSE));
44 45 46 47 48 49 50
    $this->_testImageFieldFormatters('private');
  }

  /**
   * Test image formatters on node display.
   */
  function _testImageFieldFormatters($scheme) {
51 52
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');
53
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
54
    $field_name = strtolower($this->randomMachineName());
55 56
    $field_settings = array('alt_field_required' => 0);
    $instance = $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme), $field_settings);
57

58 59 60 61 62
    // Go to manage display page.
    $this->drupalGet("admin/structure/types/manage/article/display");

    // Test for existence of link to image styles configuration.
    $this->drupalPostAjaxForm(NULL, array(), "{$field_name}_settings_edit");
63
    $this->assertLinkByHref(\Drupal::url('entity.image_style.collection'), 0, 'Link to image styles configuration is found');
64 65

    // Remove 'administer image styles' permission from testing admin user.
66
    $admin_user_roles = $this->adminUser->getRoles(TRUE);
67 68 69 70 71 72 73
    user_role_change_permissions(reset($admin_user_roles), array('administer image styles' => FALSE));

    // Go to manage display page again.
    $this->drupalGet("admin/structure/types/manage/article/display");

    // Test for absence of link to image styles configuration.
    $this->drupalPostAjaxForm(NULL, array(), "{$field_name}_settings_edit");
74
    $this->assertNoLinkByHref(\Drupal::url('entity.image_style.collection'), 'Link to image styles configuration is absent when permissions are insufficient');
75 76 77 78

    // Restore 'administer image styles' permission to testing admin user
    user_role_change_permissions(reset($admin_user_roles), array('administer image styles' => TRUE));

79 80
    // Create a new node with an image attached.
    $test_image = current($this->drupalGetTestFiles('image'));
81 82 83 84

    // Ensure that preview works.
    $this->previewNodeImage($test_image, $field_name, 'article');

85 86
    // After previewing, make the alt field required. It cannot be required
    // during preview because the form validation will fail.
87
    $instance->setSetting('alt_field_required', 1);
88 89 90 91 92
    $instance->save();

    // Create alt text for the image.
    $alt = $this->randomMachineName();

93
    // Save node.
94
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
95 96
    $node_storage->resetCache(array($nid));
    $node = $node_storage->load($nid);
97 98

    // Test that the default formatter is being used.
99 100
    $file = $node->{$field_name}->entity;
    $image_uri = $file->getFileUri();
101 102 103 104 105
    $image = array(
      '#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 40,
      '#height' => 20,
106
      '#alt' => $alt,
107
    );
108
    $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
109
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
110 111

    // Test the image linked to file formatter.
112 113 114 115
    $display_options = array(
      'type' => 'image',
      'settings' => array('image_link' => 'file'),
    );
116
    $display = entity_get_display('node', $node->getType(), 'default');
117 118 119
    $display->setComponent($field_name, $display_options)
      ->save();

120 121 122 123 124
    $image = array(
      '#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 40,
      '#height' => 20,
125
      '#alt' => $alt,
126
    );
127
    $default_output = '<a href="' . file_create_url($image_uri) . '">' . $renderer->renderRoot($image) . '</a>';
128
    $this->drupalGet('node/' . $nid);
129
    $this->assertCacheTag($file->getCacheTags()[0]);
130 131
    // @todo Remove in https://www.drupal.org/node/2646744.
    $this->assertCacheContext('url.site');
132 133
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
134
    $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
135
    // Verify that the image can be downloaded.
136
    $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
137 138 139
    if ($scheme == 'private') {
      // Only verify HTTP headers when using private scheme and the headers are
      // sent by Drupal.
140
      $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
141
      $this->assertTrue(strstr($this->drupalGetHeader('Cache-Control'), 'private') !== FALSE, 'Cache-Control header was sent.');
142 143 144 145

      // Log out and try to access the file.
      $this->drupalLogout();
      $this->drupalGet(file_create_url($image_uri));
146
      $this->assertResponse('403', 'Access denied to original image as anonymous user.');
147 148

      // Log in again.
149
      $this->drupalLogin($this->adminUser);
150 151 152
    }

    // Test the image linked to content formatter.
153 154 155
    $display_options['settings']['image_link'] = 'content';
    $display->setComponent($field_name, $display_options)
      ->save();
156 157 158 159 160 161
    $image = array(
      '#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 40,
      '#height' => 20,
    );
162
    $this->drupalGet('node/' . $nid);
163
    $this->assertCacheTag($file->getCacheTags()[0]);
164 165
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
166
    $elements = $this->xpath(
167
      '//a[@href=:path]/img[@src=:url and @alt=:alt and @width=:width and @height=:height]',
168
      array(
169
        ':path' => $node->url(),
170
        ':url' => file_url_transform_relative(file_create_url($image['#uri'])),
171 172
        ':width' => $image['#width'],
        ':height' => $image['#height'],
173
        ':alt' => $alt,
174 175 176
      )
    );
    $this->assertEqual(count($elements), 1, 'Image linked to content formatter displaying correctly on full node view.');
177 178

    // Test the image style 'thumbnail' formatter.
179 180 181 182 183
    $display_options['settings']['image_link'] = '';
    $display_options['settings']['image_style'] = 'thumbnail';
    $display->setComponent($field_name, $display_options)
      ->save();

184 185
    // Ensure the derivative image is generated so we do not have to deal with
    // image style callback paths.
186
    $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
187 188 189
    $image_style = array(
      '#theme' => 'image_style',
      '#uri' => $image_uri,
190 191
      '#width' => 40,
      '#height' => 20,
192
      '#style_name' => 'thumbnail',
193
      '#alt' => $alt,
194
    );
195
    $default_output = $renderer->renderRoot($image_style);
196
    $this->drupalGet('node/' . $nid);
197 198
    $image_style = ImageStyle::load('thumbnail');
    $this->assertCacheTag($image_style->getCacheTags()[0]);
199
    $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
200 201 202 203

    if ($scheme == 'private') {
      // Log out and try to access the file.
      $this->drupalLogout();
204
      $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
205
      $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
206 207 208 209 210 211 212
    }
  }

  /**
   * Tests for image field settings.
   */
  function testImageFieldSettings() {
213 214
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');
215
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
216 217
    $test_image = current($this->drupalGetTestFiles('image'));
    list(, $test_image_extension) = explode('.', $test_image->filename);
218
    $field_name = strtolower($this->randomMachineName());
219
    $field_settings = array(
220 221 222 223 224 225 226 227 228 229
      'alt_field' => 1,
      'file_extensions' => $test_image_extension,
      'max_filesize' => '50 KB',
      'max_resolution' => '100x100',
      'min_resolution' => '10x10',
      'title_field' => 1,
    );
    $widget_settings = array(
      'preview_image_style' => 'medium',
    );
230
    $field = $this->createImageField($field_name, 'article', array(), $field_settings, $widget_settings);
231

232 233 234
    // Verify that the min/max resolution set on the field are properly
    // extracted, and displayed, on the image field's configuration form.
    $this->drupalGet('admin/structure/types/manage/article/fields/' . $field->id());
235 236 237 238
    $this->assertFieldByName('settings[max_resolution][x]', '100', 'Expected max resolution X value of 100.');
    $this->assertFieldByName('settings[max_resolution][y]', '100', 'Expected max resolution Y value of 100.');
    $this->assertFieldByName('settings[min_resolution][x]', '10', 'Expected min resolution X value of 10.');
    $this->assertFieldByName('settings[min_resolution][y]', '10', 'Expected min resolution Y value of 10.');
239

240
    $this->drupalGet('node/add/article');
241
    $this->assertText(t('50 KB limit.'), 'Image widget max file size is displayed on article form.');
242
    $this->assertText(t('Allowed types: @extensions.', array('@extensions' => $test_image_extension)), 'Image widget allowed file types displayed on article form.');
243
    $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.');
244 245 246

    // We have to create the article first and then edit it because the alt
    // and title fields do not display until the image has been attached.
247 248 249 250 251

    // Create alt text for the image.
    $alt = $this->randomMachineName();

    $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
252
    $this->drupalGet('node/' . $nid . '/edit');
253 254
    $this->assertFieldByName($field_name . '[0][alt]', '', 'Alt field displayed on article form.');
    $this->assertFieldByName($field_name . '[0][title]', '', 'Title field displayed on article form.');
255 256
    // Verify that the attached image is being previewed using the 'medium'
    // style.
257 258
    $node_storage->resetCache(array($nid));
    $node = $node_storage->load($nid);
259
    $file = $node->{$field_name}->entity;
260

261
    $url = file_url_transform_relative(file_create_url(ImageStyle::load('medium')->buildUrl($file->getFileUri())));
262
    $this->assertTrue($this->cssSelect('img[width=40][height=20][class=image-style-medium][src="' . $url . '"]'));
263 264

    // Add alt/title fields to the image and verify that they are displayed.
265 266
    $image = array(
      '#theme' => 'image',
267
      '#uri' => $file->getFileUri(),
268
      '#alt' => $alt,
269
      '#title' => $this->randomMachineName(),
270 271
      '#width' => 40,
      '#height' => 20,
272 273
    );
    $edit = array(
274 275
      $field_name . '[0][alt]' => $image['#alt'],
      $field_name . '[0][title]' => $image['#title'],
276
    );
277
    $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
278
    $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
279
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
280 281 282 283

    // Verify that alt/title longer than allowed results in a validation error.
    $test_size = 2000;
    $edit = array(
284 285
      $field_name . '[0][alt]' => $this->randomMachineName($test_size),
      $field_name . '[0][title]' => $this->randomMachineName($test_size),
286
    );
287
    $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
288
    $schema = $field->getFieldStorageDefinition()->getSchema();
289
    $this->assertRaw(t('Alternative text cannot be longer than %max characters but is currently %length characters long.', array(
290
      '%max' => $schema['columns']['alt']['length'],
291 292 293
      '%length' => $test_size,
    )));
    $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
294
      '%max' => $schema['columns']['title']['length'],
295 296
      '%length' => $test_size,
    )));
297 298 299 300 301 302 303 304

    // Set cardinality to unlimited and add upload a second image.
    // The image widget is extending on the file widget, but the image field
    // type does not have the 'display_field' setting which is expected by
    // the file widget. This resulted in notices before when cardinality is not
    // 1, so we need to make sure the file widget prevents these notices by
    // providing all settings, even if they are not used.
    // @see FileWidget::formMultipleElements().
305
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $field_name . '/storage', array('cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED), t('Save field settings'));
306 307 308
    $edit = array(
      'files[' . $field_name . '_1][]' => drupal_realpath($test_image->uri),
    );
309
    $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save and keep published'));
310 311
    // Add the required alt text.
    $this->drupalPostForm(NULL, [$field_name . '[1][alt]' => $alt], t('Save and keep published'));
312
    $this->assertText(format_string('Article @title has been updated.', array('@title' => $node->getTitle())));
313 314 315

    // Assert ImageWidget::process() calls FieldWidget::process().
    $this->drupalGet('node/' . $node->id() . '/edit');
316 317 318
    $edit = array(
      'files[' . $field_name . '_2][]' => drupal_realpath($test_image->uri),
    );
319
    $this->drupalPostAjaxForm(NULL, $edit, $field_name . '_2_upload_button');
320 321
    $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">');
    $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">');
322 323 324 325 326 327
  }

  /**
   * Test use of a default image with an image field.
   */
  function testImageFieldDefaultImage() {
328 329 330
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->container->get('renderer');

331
    $node_storage = $this->container->get('entity.manager')->getStorage('node');
332
    // Create a new image field.
333
    $field_name = strtolower($this->randomMachineName());
334 335 336 337 338
    $this->createImageField($field_name, 'article');

    // Create a new node, with no images and verify that no images are
    // displayed.
    $node = $this->drupalCreateNode(array('type' => 'article'));
339
    $this->drupalGet('node/' . $node->id());
340 341
    // Verify that no image is displayed on the page by checking for the class
    // that would be used on the image field.
342
    $this->assertNoPattern('<div class="(.*?)field--name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
343 344
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
345

346
    // Add a default image to the public image field.
347
    $images = $this->drupalGetTestFiles('image');
348 349
    $alt = $this->randomString(512);
    $title = $this->randomString(1024);
350
    $edit = array(
351
      // Get the path of the 'image-test.png' file.
352 353 354
      'files[settings_default_image_uuid]' => drupal_realpath($images[0]->uri),
      'settings[default_image][alt]' => $alt,
      'settings[default_image][title]' => $title,
355
    );
356
    $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
357 358
    // Clear field definition cache so the new default image is detected.
    \Drupal::entityManager()->clearCachedFieldDefinitions();
359 360
    $field_storage = FieldStorageConfig::loadByName('node', $field_name);
    $default_image = $field_storage->getSetting('default_image');
361
    $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
362 363 364 365
    $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
    $image = array(
      '#theme' => 'image',
      '#uri' => $file->getFileUri(),
366 367 368 369
      '#alt' => $alt,
      '#title' => $title,
      '#width' => 40,
      '#height' => 20,
370
    );
371
    $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
372
    $this->drupalGet('node/' . $node->id());
373
    $this->assertCacheTag($file->getCacheTags()[0]);
374 375
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
376
    $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
377 378 379

    // Create a node with an image attached and ensure that the default image
    // is not displayed.
380 381 382 383

    // Create alt text for the image.
    $alt = $this->randomMachineName();

384 385
    // Upload the 'image-test.gif' file.
    $nid = $this->uploadNodeImage($images[2], $field_name, 'article', $alt);
386 387
    $node_storage->resetCache(array($nid));
    $node = $node_storage->load($nid);
388
    $file = $node->{$field_name}->entity;
389 390
    $image = array(
      '#theme' => 'image',
391
      '#uri' => $file->getFileUri(),
392 393
      '#width' => 40,
      '#height' => 20,
394
      '#alt' => $alt,
395
    );
396
    $image_output = str_replace("\n", NULL, $renderer->renderRoot($image));
397
    $this->drupalGet('node/' . $nid);
398
    $this->assertCacheTag($file->getCacheTags()[0]);
399 400
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
401 402
    $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
    $this->assertRaw($image_output, 'User supplied image is displayed.');
403 404 405

    // Remove default image from the field and make sure it is no longer used.
    $edit = array(
406
      'settings[default_image][uuid][fids]' => 0,
407
    );
408
    $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
409 410
    // Clear field definition cache so the new default image is detected.
    \Drupal::entityManager()->clearCachedFieldDefinitions();
411 412
    $field_storage = FieldStorageConfig::loadByName('node', $field_name);
    $default_image = $field_storage->getSetting('default_image');
413
    $this->assertFalse($default_image['uuid'], 'Default image removed from field.');
414 415
    // Create an image field that uses the private:// scheme and test that the
    // default image works as expected.
416
    $private_field_name = strtolower($this->randomMachineName());
417 418 419
    $this->createImageField($private_field_name, 'article', array('uri_scheme' => 'private'));
    // Add a default image to the new field.
    $edit = array(
420 421
      // Get the path of the 'image-test.gif' file.
      'files[settings_default_image_uuid]' => drupal_realpath($images[2]->uri),
422 423
      'settings[default_image][alt]' => $alt,
      'settings[default_image][title]' => $title,
424
    );
425
    $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $private_field_name . '/storage', $edit, t('Save field settings'));
426 427
    // Clear field definition cache so the new default image is detected.
    \Drupal::entityManager()->clearCachedFieldDefinitions();
428

429 430
    $private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
    $default_image = $private_field_storage->getSetting('default_image');
431
    $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
432 433
    $this->assertEqual('private', file_uri_scheme($file->getFileUri()), 'Default image uses private:// scheme.');
    $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
434 435 436
    // Create a new node with no image attached and ensure that default private
    // image is displayed.
    $node = $this->drupalCreateNode(array('type' => 'article'));
437 438 439
    $image = array(
      '#theme' => 'image',
      '#uri' => $file->getFileUri(),
440 441 442 443
      '#alt' => $alt,
      '#title' => $title,
      '#width' => 40,
      '#height' => 20,
444
    );
445
    $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
446
    $this->drupalGet('node/' . $node->id());
447
    $this->assertCacheTag($file->getCacheTags()[0]);
448 449
    $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
    $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
450
    $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');
451
  }
452

453
}