3 namespace Drupal\Tests\system\Functional\Common;
5 use Drupal\Component\Utility\UrlHelper;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Language\Language;
8 use Drupal\Core\Render\RenderContext;
10 use Drupal\Tests\BrowserTestBase;
13 * Confirm that \Drupal\Core\Url,
14 * \Drupal\Component\Utility\UrlHelper::filterQueryParameters(),
15 * \Drupal\Component\Utility\UrlHelper::buildQuery(), and
16 * \Drupal\Core\Utility\LinkGeneratorInterface::generate()
17 * work correctly with various input.
21 class UrlTest extends BrowserTestBase {
23 public static $modules = ['common_test', 'url_alter_test'];
26 * Confirms that invalid URLs are filtered in link generating functions.
28 public function testLinkXSS() {
30 $text = $this->randomMachineName();
31 $path = "<SCRIPT>alert('XSS')</SCRIPT>";
32 $encoded_path = "3CSCRIPT%3Ealert%28%27XSS%27%29%3C/SCRIPT%3E";
34 $link = \Drupal::l($text, Url::fromUserInput('/' . $path));
35 $this->assertTrue(strpos($link, $encoded_path) !== FALSE && strpos($link, $path) === FALSE, format_string('XSS attack @path was filtered by \Drupal\Core\Utility\LinkGeneratorInterface::generate().', ['@path' => $path]));
37 // Test \Drupal\Core\Url.
38 $link = Url::fromUri('base:' . $path)->toString();
39 $this->assertTrue(strpos($link, $encoded_path) !== FALSE && strpos($link, $path) === FALSE, format_string('XSS attack @path was filtered by #theme', ['@path' => $path]));
43 * Tests that #type=link bubbles outbound route/path processors' metadata.
45 public function testLinkBubbleableMetadata() {
47 ['Regular link', 'internal:/user', [], ['contexts' => [], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
48 ['Regular link, absolute', 'internal:/user', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => [], 'max-age' => Cache::PERMANENT], []],
49 ['Route processor link', 'route:system.run_cron', [], ['contexts' => ['session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
50 ['Route processor link, absolute', 'route:system.run_cron', ['absolute' => TRUE], ['contexts' => ['url.site', 'session'], 'tags' => [], 'max-age' => Cache::PERMANENT], ['placeholders' => []]],
51 ['Path processor link', 'internal:/user/1', [], ['contexts' => [], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
52 ['Path processor link, absolute', 'internal:/user/1', ['absolute' => TRUE], ['contexts' => ['url.site'], 'tags' => ['user:1'], 'max-age' => Cache::PERMANENT], []],
55 foreach ($cases as $case) {
56 list($title, $uri, $options, $expected_cacheability, $expected_attachments) = $case;
57 $expected_cacheability['contexts'] = Cache::mergeContexts($expected_cacheability['contexts'], ['languages:language_interface', 'theme', 'user.permissions']);
61 '#options' => $options,
62 '#url' => Url::fromUri($uri),
64 \Drupal::service('renderer')->renderRoot($link);
66 $this->assertEqual($expected_cacheability, $link['#cache']);
67 $this->assertEqual($expected_attachments, $link['#attached']);
72 * Tests that default and custom attributes are handled correctly on links.
74 public function testLinkAttributes() {
75 /** @var \Drupal\Core\Render\RendererInterface $renderer */
76 $renderer = $this->container->get('renderer');
78 // Test that hreflang is added when a link has a known language.
79 $language = new Language(['id' => 'fr', 'name' => 'French']);
83 'language' => $language,
85 '#url' => Url::fromUri('https://www.drupal.org'),
88 $langcode = $language->getId();
90 // Test that the default hreflang handling for links does not override a
91 // hreflang attribute explicitly set in the render array.
92 $hreflang_override_link = $hreflang_link;
93 $hreflang_override_link['#options']['attributes']['hreflang'] = 'foo';
95 $rendered = $renderer->renderRoot($hreflang_link);
96 $this->assertTrue($this->hasAttribute('hreflang', $rendered, $langcode), format_string('hreflang attribute with value @langcode is present on a rendered link when langcode is provided in the render array.', ['@langcode' => $langcode]));
98 $rendered = $renderer->renderRoot($hreflang_override_link);
99 $this->assertTrue($this->hasAttribute('hreflang', $rendered, 'foo'), format_string('hreflang attribute with value @hreflang is present on a rendered link when @hreflang is provided in the render array.', ['@hreflang' => 'foo']));
101 // Test the active class in links produced by
102 // \Drupal\Core\Utility\LinkGeneratorInterface::generate() and #type 'link'.
103 $options_no_query = [];
110 $options_query_reverse = [
118 $path = 'common-test/type-link-active-class';
120 $this->drupalGet($path, $options_no_query);
121 $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', [':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'is-active']);
122 $this->assertTrue(isset($links[0]), 'A link generated by the link generator to the current page is marked active.');
124 $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', [':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'is-active']);
125 $this->assertTrue(isset($links[0]), 'A link generated by the link generator to the current page with a query string when the current page has no query string is not marked active.');
127 $this->drupalGet($path, $options_query);
128 $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', [':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'is-active']);
129 $this->assertTrue(isset($links[0]), 'A link generated by the link generator to the current page with a query string that matches the current query string is marked active.');
131 $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', [':href' => Url::fromRoute('common_test.l_active_class', [], $options_query_reverse)->toString(), ':class' => 'is-active']);
132 $this->assertTrue(isset($links[0]), 'A link generated by the link generator to the current page with a query string that has matching parameters to the current query string but in a different order is marked active.');
134 $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', [':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'is-active']);
135 $this->assertTrue(isset($links[0]), 'A link generated by the link generator to the current page without a query string when the current page has a query string is not marked active.');
137 // Test adding a custom class in links produced by
138 // \Drupal\Core\Utility\LinkGeneratorInterface::generate() and #type 'link'.
139 // Test the link generator.
140 $class_l = $this->randomMachineName();
141 $link_l = \Drupal::l($this->randomMachineName(), new Url('<current>', [], ['attributes' => ['class' => [$class_l]]]));
142 $this->assertTrue($this->hasAttribute('class', $link_l, $class_l), format_string('Custom class @class is present on link when requested by l()', ['@class' => $class_l]));
145 $class_theme = $this->randomMachineName();
148 '#title' => $this->randomMachineName(),
149 '#url' => Url::fromRoute('<current>'),
152 'class' => [$class_theme],
156 $link_theme = $renderer->renderRoot($type_link);
157 $this->assertTrue($this->hasAttribute('class', $link_theme, $class_theme), format_string('Custom class @class is present on link when requested by #type', ['@class' => $class_theme]));
161 * Tests that link functions support render arrays as 'text'.
163 public function testLinkRenderArrayText() {
164 /** @var \Drupal\Core\Render\RendererInterface $renderer */
165 $renderer = $this->container->get('renderer');
167 // Build a link with the link generator for reference.
168 $l = \Drupal::l('foo', Url::fromUri('https://www.drupal.org'));
170 // Test a renderable array passed to the link generator.
171 $renderer->executeInRenderContext(new RenderContext(), function () use ($renderer, $l) {
172 $renderable_text = ['#markup' => 'foo'];
173 $l_renderable_text = \Drupal::l($renderable_text, Url::fromUri('https://www.drupal.org'));
174 $this->assertEqual($l_renderable_text, $l);
177 // Test a themed link with plain text 'text'.
178 $type_link_plain_array = [
181 '#url' => Url::fromUri('https://www.drupal.org'),
183 $type_link_plain = $renderer->renderRoot($type_link_plain_array);
184 $this->assertEqual($type_link_plain, $l);
186 // Build a themed link with renderable 'text'.
187 $type_link_nested_array = [
189 '#title' => ['#markup' => 'foo'],
190 '#url' => Url::fromUri('https://www.drupal.org'),
192 $type_link_nested = $renderer->renderRoot($type_link_nested_array);
193 $this->assertEqual($type_link_nested, $l);
197 * Checks for class existence in link.
202 * Element class to search for.
205 * TRUE if the class is found, FALSE otherwise.
207 private function hasAttribute($attribute, $link, $class) {
208 return preg_match('|' . $attribute . '="([^\"\s]+\s+)*' . $class . '|', $link);
212 * Tests UrlHelper::filterQueryParameters().
214 public function testDrupalGetQueryParameters() {
226 // First-level exclusion.
229 $this->assertEqual(UrlHelper::filterQueryParameters($original, ['b']), $result, "'b' was removed.");
231 // Second-level exclusion.
233 unset($result['b']['d']);
234 $this->assertEqual(UrlHelper::filterQueryParameters($original, ['b[d]']), $result, "'b[d]' was removed.");
236 // Third-level exclusion.
238 unset($result['b']['e']['f']);
239 $this->assertEqual(UrlHelper::filterQueryParameters($original, ['b[e][f]']), $result, "'b[e][f]' was removed.");
241 // Multiple exclusions.
243 unset($result['a'], $result['b']['e'], $result['c']);
244 $this->assertEqual(UrlHelper::filterQueryParameters($original, ['a', 'b[e]', 'c']), $result, "'a', 'b[e]', 'c' were removed.");
248 * Tests UrlHelper::parse().
250 public function testDrupalParseUrl() {
251 // Relative, absolute, and external URLs, without/with explicit script path,
252 // without/with Drupal path.
253 foreach (['', '/', 'https://www.drupal.org/'] as $absolute) {
254 foreach (['', 'index.php/'] as $script) {
255 foreach (['', 'foo/bar'] as $path) {
256 $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
258 'path' => $absolute . $script . $path,
259 'query' => ['foo' => 'bar', 'bar' => 'baz', 'baz' => ''],
262 $this->assertEqual(UrlHelper::parse($url), $expected, 'URL parsed correctly.');
267 // Relative URL that is known to confuse parse_url().
270 'path' => 'foo/bar:1',
274 $this->assertEqual(UrlHelper::parse($url), $result, 'Relative URL parsed correctly.');
276 // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
277 $url = 'https://www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
278 $this->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');
280 // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
281 $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
282 $this->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\Drupal\Component\Utility\UrlHelper::isValid() correctly parsed a forged URL.');
286 * Tests external URL handling.
288 public function testExternalUrls() {
289 $test_url = 'https://www.drupal.org/';
291 // Verify external URL can contain a fragment.
292 $url = $test_url . '#drupal';
293 $result = Url::fromUri($url)->toString();
294 $this->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');
296 // Verify fragment can be overridden in an external URL.
297 $url = $test_url . '#drupal';
298 $fragment = $this->randomMachineName(10);
299 $result = Url::fromUri($url, ['fragment' => $fragment])->toString();
300 $this->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overridden with a custom fragment in $options.');
302 // Verify external URL can contain a query string.
303 $url = $test_url . '?drupal=awesome';
304 $result = Url::fromUri($url)->toString();
305 $this->assertEqual($url, $result);
307 // Verify external URL can be extended with a query string.
309 $query = ['awesome' => 'drupal'];
310 $result = Url::fromUri($url, ['query' => $query])->toString();
311 $this->assertSame('https://www.drupal.org/?awesome=drupal', $result);
313 // Verify query string can be extended in an external URL.
314 $url = $test_url . '?drupal=awesome';
315 $query = ['awesome' => 'drupal'];
316 $result = Url::fromUri($url, ['query' => $query])->toString();
317 $this->assertEqual('https://www.drupal.org/?drupal=awesome&awesome=drupal', $result);