UrlTest.php 11.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

/**
 * @file
 * Definition of Drupal\system\Tests\Common\UrlTest.
 */

namespace Drupal\system\Tests\Common;

10
use Drupal\Component\Utility\UrlHelper;
11
use Drupal\Core\Language\Language;
12
use Drupal\Core\Url;
13 14 15
use Drupal\simpletest\WebTestBase;

/**
16
 * Confirm that \Drupal\Core\Url,
17
 * \Drupal\Component\Utility\UrlHelper::filterQueryParameters(),
18
 * \Drupal\Component\Utility\UrlHelper::buildQuery(), and _l() work correctly
19
 * with various input.
20
 *
21
 * @group Common
22 23
 */
class UrlTest extends WebTestBase {
24 25 26

  public static $modules = array('common_test');

27
  /**
28
   * Confirms that invalid URLs are filtered in link generating functions.
29
   */
30
  function testLinkXSS() {
31
    // Test _l().
32
    $text = $this->randomMachineName();
33
    $path = "<SCRIPT>alert('XSS')</SCRIPT>";
34
    $link = _l($text, $path);
35
    $sanitized_path = check_url(Url::fromUri('base://' . $path)->toString());
36
    $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, format_string('XSS attack @path was filtered by _l().', array('@path' => $path)));
37

38 39 40
    // Test \Drupal\Core\Url.
    $link = Url::fromUri('base://' . $path)->toString();
    $sanitized_path = check_url(Url::fromUri('base://' . $path)->toString());
41
    $this->assertTrue(strpos($link, $sanitized_path) !== FALSE, format_string('XSS attack @path was filtered by #theme', ['@path' => $path]));
42 43
  }

44
  /**
45
   * Tests that default and custom attributes are handled correctly on links.
46
   */
47 48 49 50 51 52 53 54
  function testLinkAttributes() {
    // Test that hreflang is added when a link has a known language.
    $language = new Language(array('id' => 'fr', 'name' => 'French'));
    $hreflang_link = array(
      '#type' => 'link',
      '#options' => array(
        'language' => $language,
      ),
55
      '#url' => Url::fromUri('http://drupal.org'),
56 57
      '#title' => 'bar',
    );
58
    $langcode = $language->getId();
59 60 61 62 63 64 65 66 67 68 69 70

    // Test that the default hreflang handling for links does not override a
    // hreflang attribute explicitly set in the render array.
    $hreflang_override_link = $hreflang_link;
    $hreflang_override_link['#options']['attributes']['hreflang'] = 'foo';

    $rendered = drupal_render($hreflang_link);
    $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.', array('@langcode' => $langcode)));

    $rendered = drupal_render($hreflang_override_link);
    $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.', array('@hreflang' => 'foo')));

71
    // Test the active class in links produced by _l() and #type 'link'.
72 73 74 75 76 77 78 79 80 81 82 83 84 85
    $options_no_query = array();
    $options_query = array(
      'query' => array(
        'foo' => 'bar',
        'one' => 'two',
      ),
    );
    $options_query_reverse = array(
      'query' => array(
        'one' => 'two',
        'foo' => 'bar',
      ),
    );

86 87
    // Test #type link.
    $path = 'common-test/type-link-active-class';
88

89
    $this->drupalGet($path, $options_no_query);
90
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'active'));
91
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page is marked active.');
92

93
    $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'active'));
94
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page with a query string when the current page has no query string is not marked active.');
95 96

    $this->drupalGet($path, $options_query);
97
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query)->toString(), ':class' => 'active'));
98
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page with a query string that matches the current query string is marked active.');
99

100
    $links = $this->xpath('//a[@href = :href and contains(@class, :class)]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_query_reverse)->toString(), ':class' => 'active'));
101
    $this->assertTrue(isset($links[0]), 'A link generated by _l() 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.');
102

103
    $links = $this->xpath('//a[@href = :href and not(contains(@class, :class))]', array(':href' => Url::fromRoute('common_test.l_active_class', [], $options_no_query)->toString(), ':class' => 'active'));
104
    $this->assertTrue(isset($links[0]), 'A link generated by _l() to the current page without a query string when the current page has a query string is not marked active.');
105

106 107
    // Test adding a custom class in links produced by _l() and #type 'link'.
    // Test _l().
108
    $class_l = $this->randomMachineName();
109 110
    $link_l = \Drupal::l($this->randomMachineName(), new Url('<current>', [], ['attributes' => ['class' => [$class_l]]]));
    $this->assertTrue($this->hasAttribute('class', $link_l, $class_l), format_string('Custom class @class is present on link when requested by l()', array('@class' => $class_l)));
111

112
    // Test #type.
113
    $class_theme = $this->randomMachineName();
114 115
    $type_link = array(
      '#type' => 'link',
116
      '#title' => $this->randomMachineName(),
117
      '#url' => Url::fromRoute('<current>'),
118 119 120 121 122 123
      '#options' => array(
        'attributes' => array(
          'class' => array($class_theme),
        ),
      ),
    );
124
    $link_theme = drupal_render($type_link);
125
    $this->assertTrue($this->hasAttribute('class', $link_theme, $class_theme), format_string('Custom class @class is present on link when requested by #type', array('@class' => $class_theme)));
126 127 128
  }

  /**
129
   * Tests that link functions support render arrays as 'text'.
130
   */
131
  function testLinkRenderArrayText() {
132
    // Build a link with _l() for reference.
133
    $l = \Drupal::l('foo', Url::fromUri('http://drupal.org'));
134

135
    // Test a renderable array passed to _l().
136
    $renderable_text = array('#markup' => 'foo');
137
    $l_renderable_text = \Drupal::l($renderable_text, Url::fromUri('http://drupal.org'));
138 139
    $this->assertEqual($l_renderable_text, $l);

140
    // Test a themed link with plain text 'text'.
141 142 143
    $type_link_plain_array = array(
      '#type' => 'link',
      '#title' => 'foo',
144
      '#url' => Url::fromUri('http://drupal.org'),
145
    );
146 147
    $type_link_plain = drupal_render($type_link_plain_array);
    $this->assertEqual($type_link_plain, $l);
148 149

    // Build a themed link with renderable 'text'.
150 151 152
    $type_link_nested_array = array(
      '#type' => 'link',
      '#title' => array('#markup' => 'foo'),
153
      '#url' => Url::fromUri('http://drupal.org'),
154
    );
155 156
    $type_link_nested = drupal_render($type_link_nested_array);
    $this->assertEqual($type_link_nested, $l);
157 158
  }

159 160 161 162 163 164 165 166 167 168 169
  /**
   * Checks for class existence in link.
   *
   * @param $link
   *   URL to search.
   * @param $class
   *   Element class to search for.
   *
   * @return bool
   *   TRUE if the class is found, FALSE otherwise.
   */
170 171
  private function hasAttribute($attribute, $link, $class) {
    return preg_match('|' . $attribute . '="([^\"\s]+\s+)*' . $class . '|', $link);
172 173 174
  }

  /**
175
   * Tests UrlHelper::filterQueryParameters().
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
   */
  function testDrupalGetQueryParameters() {
    $original = array(
      'a' => 1,
      'b' => array(
        'd' => 4,
        'e' => array(
          'f' => 5,
        ),
      ),
      'c' => 3,
    );

    // First-level exclusion.
    $result = $original;
    unset($result['b']);
192
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b')), $result, "'b' was removed.");
193 194 195 196

    // Second-level exclusion.
    $result = $original;
    unset($result['b']['d']);
197
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b[d]')), $result, "'b[d]' was removed.");
198 199 200 201

    // Third-level exclusion.
    $result = $original;
    unset($result['b']['e']['f']);
202
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('b[e][f]')), $result, "'b[e][f]' was removed.");
203 204 205 206

    // Multiple exclusions.
    $result = $original;
    unset($result['a'], $result['b']['e'], $result['c']);
207
    $this->assertEqual(UrlHelper::filterQueryParameters($original, array('a', 'b[e]', 'c')), $result, "'a', 'b[e]', 'c' were removed.");
208 209 210
  }

  /**
211
   * Tests UrlHelper::parse().
212 213 214 215 216 217 218 219 220 221 222 223 224
   */
  function testDrupalParseUrl() {
    // Relative, absolute, and external URLs, without/with explicit script path,
    // without/with Drupal path.
    foreach (array('', '/', 'http://drupal.org/') as $absolute) {
      foreach (array('', 'index.php/') as $script) {
        foreach (array('', 'foo/bar') as $path) {
          $url = $absolute . $script . $path . '?foo=bar&bar=baz&baz#foo';
          $expected = array(
            'path' => $absolute . $script . $path,
            'query' => array('foo' => 'bar', 'bar' => 'baz', 'baz' => ''),
            'fragment' => 'foo',
          );
225
          $this->assertEqual(UrlHelper::parse($url), $expected, 'URL parsed correctly.');
226 227 228 229 230 231 232 233 234 235 236
        }
      }
    }

    // Relative URL that is known to confuse parse_url().
    $url = 'foo/bar:1';
    $result = array(
      'path' => 'foo/bar:1',
      'query' => array(),
      'fragment' => '',
    );
237
    $this->assertEqual(UrlHelper::parse($url), $result, 'Relative URL parsed correctly.');
238 239 240

    // Test that drupal can recognize an absolute URL. Used to prevent attack vectors.
    $url = 'http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo';
241
    $this->assertTrue(UrlHelper::isExternal($url), 'Correctly identified an external URL.');
242

243 244 245
    // Test that UrlHelper::parse() does not allow spoofing a URL to force a malicious redirect.
    $parts = UrlHelper::parse('forged:http://cwe.mitre.org/data/definitions/601.html');
    $this->assertFalse(UrlHelper::isValid($parts['path'], TRUE), '\Drupal\Component\Utility\UrlHelper::isValid() correctly parsed a forged URL.');
246 247 248
  }

  /**
249
   * Tests external URL handling.
250 251 252 253 254 255
   */
  function testExternalUrls() {
    $test_url = 'http://drupal.org/';

    // Verify external URL can contain a fragment.
    $url = $test_url . '#drupal';
256
    $result = Url::fromUri($url)->toString();
257
    $this->assertEqual($url, $result, 'External URL with fragment works without a fragment in $options.');
258 259 260

    // Verify fragment can be overidden in an external URL.
    $url = $test_url . '#drupal';
261
    $fragment = $this->randomMachineName(10);
262
    $result = Url::fromUri($url, array('fragment' => $fragment))->toString();
263
    $this->assertEqual($test_url . '#' . $fragment, $result, 'External URL fragment is overidden with a custom fragment in $options.');
264 265 266

    // Verify external URL can contain a query string.
    $url = $test_url . '?drupal=awesome';
267
    $result = Url::fromUri($url)->toString();
268
    $this->assertEqual($url, $result, 'External URL with query string works without a query string in $options.');
269 270 271

    // Verify external URL can be extended with a query string.
    $url = $test_url;
272
    $query = array($this->randomMachineName(5) => $this->randomMachineName(5));
273
    $result = Url::fromUri($url, array('query' => $query))->toString();
274
    $this->assertEqual($url . '?' . http_build_query($query, '', '&'), $result, 'External URL can be extended with a query string in $options.');
275 276 277

    // Verify query string can be extended in an external URL.
    $url = $test_url . '?drupal=awesome';
278
    $query = array($this->randomMachineName(5) => $this->randomMachineName(5));
279
    $result = Url::fromUri($url, array('query' => $query))->toString();
280
    $this->assertEqual($url . '&' . http_build_query($query, '', '&'), $result, 'External URL query string can be extended with a custom query string in $options.');
281 282
  }
}