ImageStylesPathAndUrlTest.php 10.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Definition of Drupal\image\Tests\ImageStylesPathAndUrlTest.
 */

namespace Drupal\image\Tests;

use Drupal\simpletest\WebTestBase;
11
use Symfony\Component\HttpFoundation\Request;
12 13 14 15 16

/**
 * Tests the functions for generating paths and URLs for image styles.
 */
class ImageStylesPathAndUrlTest extends WebTestBase {
17 18 19 20 21 22 23 24

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('image', 'image_module_test');

25 26 27 28
  /**
   * @var \Drupal\image\ImageStyleInterface
   */
  protected $style;
29 30 31 32 33 34 35 36 37 38

  public static function getInfo() {
    return array(
      'name' => 'Image styles path and URL functions',
      'description' => 'Tests functions for generating paths and URLs to image styles.',
      'group' => 'Image',
    );
  }

  function setUp() {
39
    parent::setUp();
40

41 42
    $this->style = entity_create('image_style', array('name' => 'style_foo', 'label' => $this->randomString()));
    $this->style->save();
43 44 45
  }

  /**
46
   * Tests \Drupal\image\ImageStyleInterface::buildUri().
47 48 49
   */
  function testImageStylePath() {
    $scheme = 'public';
50 51
    $actual = $this->style->buildUri("$scheme://foo/bar.gif");
    $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
52
    $this->assertEqual($actual, $expected, 'Got the path for a file URI.');
53

54 55
    $actual = $this->style->buildUri('foo/bar.gif');
    $expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
56
    $this->assertEqual($actual, $expected, 'Got the path for a relative file path.');
57 58 59
  }

  /**
60
   * Tests an image style URL using the "public://" scheme.
61 62
   */
  function testImageStyleUrlAndPathPublic() {
63
    $this->doImageStyleUrlAndPathTests('public');
64 65 66
  }

  /**
67
   * Tests an image style URL using the "private://" scheme.
68 69
   */
  function testImageStyleUrlAndPathPrivate() {
70
    $this->doImageStyleUrlAndPathTests('private');
71 72 73
  }

  /**
74
   * Tests an image style URL with the "public://" scheme and unclean URLs.
75
   */
76 77
   function testImageStyleUrlAndPathPublicUnclean() {
     $this->doImageStyleUrlAndPathTests('public', FALSE);
78 79 80
   }

  /**
81
   * Tests an image style URL with the "private://" schema and unclean URLs.
82 83
   */
  function testImageStyleUrlAndPathPrivateUnclean() {
84
    $this->doImageStyleUrlAndPathTests('private', FALSE);
85 86 87
  }

  /**
88
   * Tests an image style URL with a file URL that has an extra slash in it.
89
   */
90
  function testImageStyleUrlExtraSlash() {
91
    $this->doImageStyleUrlAndPathTests('public', TRUE, TRUE);
92 93
  }

94 95 96 97 98
  /**
   * Tests that an invalid source image returns a 404.
   */
  function testImageStyleUrlForMissingSourceImage() {
    $non_existent_uri = 'public://foo.png';
99
    $generated_url = $this->style->buildUrl($non_existent_uri);
100 101 102 103
    $this->drupalGet($generated_url);
    $this->assertResponse(404, 'Accessing an image style URL with a source image that does not exist provides a 404 error response.');
  }

104
  /**
105
   * Tests building an image style URL.
106
   */
107 108
  function doImageStyleUrlAndPathTests($scheme, $clean_url = TRUE, $extra_slash = FALSE) {
    $this->prepareRequestForGenerator($clean_url);
109 110 111

    // Make the default scheme neither "public" nor "private" to verify the
    // functions work for other than the default scheme.
112
    \Drupal::config('system.file')->set('default_scheme', 'temporary')->save();
113 114

    // Create the directories for the styles.
115
    $directory = $scheme . '://styles/' . $this->style->id();
116
    $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
117
    $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
118 119 120

    // Create a working copy of the file.
    $files = $this->drupalGetTestFiles('image');
121
    $file = array_shift($files);
122 123 124
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
    // Let the image_module_test module know about this file, so it can claim
    // ownership in hook_file_download().
125
    \Drupal::state()->set('image.test_file_download', $original_uri);
126
    $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
127 128

    // Get the URL of a file that has not been generated and try to create it.
129
    $generated_uri = $this->style->buildUri($original_uri);
130
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
131
    $generate_url = $this->style->buildUrl($original_uri, $clean_url);
132

133 134 135 136 137 138
    // Ensure that the tests still pass when the file is generated by accessing
    // a poorly constructed (but still valid) file URL that has an extra slash
    // in it.
    if ($extra_slash) {
      $modified_uri = str_replace('://', ':///', $original_uri);
      $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
139
      $generate_url = $this->style->buildUrl($modified_uri, $clean_url);
140
    }
141 142
    if (!$clean_url) {
      $this->assertTrue(strpos($generate_url, 'index.php/') !== FALSE, 'When using non-clean URLS, the system path contains the script name.');
143
    }
144 145
    // Add some extra chars to the token.
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
146
    $this->assertResponse(403, 'Image was inaccessible at the URL with an invalid token.');
147 148
    // Change the parameter name so the token is missing.
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
149
    $this->assertResponse(403, 'Image was inaccessible at the URL with a missing token.');
150

151 152 153 154 155 156 157 158 159 160
    // Check that the generated URL is the same when we pass in a relative path
    // rather than a URI. We need to temporarily switch the default scheme to
    // match the desired scheme before testing this, then switch it back to the
    // "temporary" scheme used throughout this test afterwards.
    \Drupal::config('system.file')->set('default_scheme', $scheme)->save();
    $relative_path = file_uri_target($original_uri);
    $generate_url_from_relative_path = $this->style->buildUrl($relative_path, $clean_url);
    $this->assertEqual($generate_url, $generate_url_from_relative_path);
    \Drupal::config('system.file')->set('default_scheme', 'temporary')->save();

161 162
    // Fetch the URL that generates the file.
    $this->drupalGet($generate_url);
163 164 165
    $this->assertResponse(200, 'Image was generated at the URL.');
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
    $this->assertRaw(file_get_contents($generated_uri), 'URL returns expected file.');
166 167 168
    $image = $this->container->get('image.factory')->get($generated_uri);
    $this->assertEqual($this->drupalGetHeader('Content-Type'), $image->getMimeType(), 'Expected Content-Type was reported.');
    $this->assertEqual($this->drupalGetHeader('Content-Length'), $image->getFileSize(), 'Expected Content-Length was reported.');
169
    if ($scheme == 'private') {
170
      $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
171
      $this->assertNotEqual(strpos($this->drupalGetHeader('Cache-Control'), 'no-cache'), FALSE, 'Cache-Control header contains \'no-cache\' to prevent caching.');
172
      $this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
173

174 175
      // Make sure that a second request to the already existing derivative
      // works too.
176
      $this->drupalGet($generate_url);
177
      $this->assertResponse(200, 'Image was generated at the URL.');
178

179 180
      // Make sure that access is denied for existing style files if we do not
      // have access.
181
      \Drupal::state()->delete('image.test_file_download');
182 183 184
      $this->drupalGet($generate_url);
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');

185 186 187 188
      // Repeat this with a different file that we do not have access to and
      // make sure that access is denied.
      $file_noaccess = array_shift($files);
      $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
189
      $generated_uri_noaccess = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/'. drupal_basename($original_uri_noaccess);
190
      $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
191
      $generate_url_noaccess = $this->style->buildUrl($original_uri_noaccess);
192 193

      $this->drupalGet($generate_url_noaccess);
194
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
195 196 197 198 199 200 201 202 203
      // Verify that images are not appended to the response. Currently this test only uses PNG images.
      if (strpos($generate_url, '.png') === FALSE ) {
        $this->fail('Confirming that private image styles are not appended require PNG file.');
      }
      else {
        // Check for PNG-Signature (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2) in the
        // response body.
        $this->assertNoRaw( chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10), 'No PNG signature found in the response body.');
      }
204
    }
205
    elseif ($clean_url) {
206 207
      // Add some extra chars to the token.
      $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
208
      $this->assertResponse(200, 'Existing image was accessible at the URL with an invalid token.');
209
    }
210

211 212
    // Allow insecure image derivatives to be created for the remainder of this
    // test.
213
    \Drupal::config('image.settings')->set('allow_insecure_derivatives', TRUE)->save();
214 215 216 217 218 219 220

    // Create another working copy of the file.
    $files = $this->drupalGetTestFiles('image');
    $file = array_shift($files);
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
    // Let the image_module_test module know about this file, so it can claim
    // ownership in hook_file_download().
221
    \Drupal::state()->set('image.test_file_download', $original_uri);
222 223 224 225

    // Suppress the security token in the URL, then get the URL of a file that
    // has not been created and try to create it. Check that the security token
    // is not present in the URL but that the image is still accessible.
226
    \Drupal::config('image.settings')->set('suppress_itok_output', TRUE)->save();
227
    $generated_uri = $this->style->buildUri($original_uri);
228
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
229
    $generate_url = $this->style->buildUrl($original_uri, $clean_url);
230 231 232
    $this->assertIdentical(strpos($generate_url, IMAGE_DERIVATIVE_TOKEN . '='), FALSE, 'The security token does not appear in the image style URL.');
    $this->drupalGet($generate_url);
    $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
233
  }
234

235
}