isExternal example

// The destination is removed rather than sanitized because the URL         // generator service is not available and this method is called very         // early in the bootstrap.         $bag->remove('destination');
        $sanitized = TRUE;
        if ($log_sanitized_keys) {
          trigger_error(sprintf('Potentially unsafe destination removed from %s parameter bag because it contained the following keys: %s', $bag_nameimplode(', ', $destination_dangerous_keys)));
        }
      }
      // Sanitize the destination parameter (which is often used for redirects)       // to prevent open redirect attacks leading to other domains.       if (UrlHelper::isExternal($destination)) {
        // The destination is removed because it is an external URL.         $bag->remove('destination');
        $sanitized = TRUE;
        if ($log_sanitized_keys) {
          trigger_error(sprintf('Potentially unsafe destination removed from %s parameter bag because it points to an external URL.', $bag_name));
        }
      }
    }
    return $sanitized;
  }

  
public function validate($value, Constraint $constraint) {
    if (isset($value)) {
      try {
        /** @var \Drupal\Core\Url $url */
        $url = $value->getUrl();
      }
      // If the URL is malformed this constraint cannot check further.       catch (\InvalidArgumentException $e) {
        return;
      }
      // Disallow external URLs using untrusted protocols.       if ($url->isExternal() && !in_array(parse_url($url->getUri(), PHP_URL_SCHEME), UrlHelper::getAllowedProtocols())) {
        $this->context->addViolation($constraint->message, ['@uri' => $value->uri]);
      }
    }
  }

}

  public function isEmpty() {
    $value = $this->get('uri')->getValue();
    return $value === NULL || $value === '';
  }

  /** * {@inheritdoc} */
  public function isExternal() {
    return $this->getUrl()->isExternal();
  }

  /** * {@inheritdoc} */
  public static function mainPropertyName() {
    return 'uri';
  }

  /** * {@inheritdoc} */

  private function translateLibraryPaths(array $overrides, string $component_directory): array {
    // We only alter the keys of the CSS and JS entries.     $altered_overrides = $overrides;
    unset($altered_overrides['css']$altered_overrides['js']);
    $css = $overrides['css'] ?? [];
    $js = $overrides['js'] ?? [];
    foreach ($css as $dir => $css_info) {
      foreach ($css_info as $filename => $options) {
        if (!UrlHelper::isExternal($filename)) {
          $absolute_filename = sprintf('%s%s%s', $component_directory, DIRECTORY_SEPARATOR, $filename);
          $altered_filename = $this->makePathRelativeToLibraryRoot($absolute_filename);
          $altered_overrides['css'][$dir][$altered_filename] = $options;
        }
        else {
          $altered_overrides['css'][$dir][$filename] = $options;
        }
      }
    }
    foreach ($js as $filename => $options) {
      if (!UrlHelper::isExternal($filename)) {
        

    // The URL generator service is not necessarily available yet; e.g., in     // interactive installer tests.     elseif (\Drupal::hasService('url_generator')) {
      // Strip $base_path, if existent.       $length = strlen($base_path);
      if (substr($path, 0, $length) === $base_path) {
        $path = substr($path$length);
      }

      $force_internal = isset($options['external']) && $options['external'] == FALSE;
      if (!$force_internal && UrlHelper::isExternal($path)) {
        return Url::fromUri($path$options)->toString();
      }
      else {
        $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
        // Path processing is needed for language prefixing. Skip it when a         // path that may look like an external URL is being used as internal.         $options['path_processing'] = !$force_internal;
        return Url::fromUri($uri$options)
          ->setAbsolute()
          ->toString();
      }
    }
// Relative URL that is known to confuse parse_url().     $url = 'foo/bar:1';
    $result = [
      'path' => 'foo/bar:1',
      'query' => [],
      'fragment' => '',
    ];
    $this->assertEquals($result, UrlHelper::parse($url), 'Relative URL parsed correctly.');

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

    // 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.');
  }

  /** * Tests external URL handling. */
  public function testExternalUrls() {
    $test_url = 'https://www.drupal.org/';

    

  public function testIsExternal($path$expected) {
    $isExternal = UrlHelper::isExternal($path);
    $this->assertEquals($expected$isExternal);
  }

  /** * Provides data for self::testIsExternal(). * * @return array */
  public static function providerTestIsExternal() {
    return [
      ['/internal/path', FALSE],
      [
/** * Determines whether a path is local. * * @param string $url * The internal path or external URL being linked to, such as "node/34" or * "http://example.com/foo". * * @return bool * TRUE or FALSE, where TRUE indicates a local path. */
  protected function isLocal($url) {
    return !UrlHelper::isExternal($url) || UrlHelper::externalIsLocal($url$this->getRequestContext()->getCompleteBaseUrl());
  }

  /** * Returns the request context. * * @return \Drupal\Core\Routing\RequestContext * The request context. */
  protected function getRequestContext() {
    if (!isset($this->requestContext)) {
      $this->requestContext = \Drupal::service('router.request_context');
    }
      try {
        $url = $link_item->getUrl();
      }
      catch (\InvalidArgumentException $e) {
        $uri_is_valid = FALSE;
      }

      // If the link field doesn't support both internal and external links,       // check whether the URL (a resolved URI) is in fact violating either       // restriction.       if ($uri_is_valid && $link_type !== LinkItemInterface::LINK_GENERIC) {
        if (!($link_type & LinkItemInterface::LINK_EXTERNAL) && $url->isExternal()) {
          $uri_is_valid = FALSE;
        }
        if (!($link_type & LinkItemInterface::LINK_INTERNAL) && !$url->isExternal()) {
          $uri_is_valid = FALSE;
        }
      }

      if (!$uri_is_valid) {
        $this->context->addViolation($constraint->message, ['@uri' => $link_item->uri]);
      }
    }
  }


  /** * Tests the isExternal() method. * * @depends testUrlFromRequest * * @covers ::isExternal */
  public function testIsExternal($urls) {
    foreach ($urls as $url) {
      $this->assertFalse($url->isExternal());
    }
  }

  /** * Tests the getUri() method for internal URLs. * * @param \Drupal\Core\Url[] $urls * Array of URL objects. * * @depends testUrlFromRequest * * @covers ::getUri */

    if (!empty($parsed_url['fragment'])) {
      $options['fragment'] = $parsed_url['fragment'];
    }

    if ($parsed_url['path'] == '<front>') {
      return new Url('<front>', []$options);
    }
    elseif ($parsed_url['path'] == '<none>') {
      return new Url('<none>', []$options);
    }
    elseif (UrlHelper::isExternal($path) && UrlHelper::isValid($path)) {
      if (empty($parsed_url['path'])) {
        return FALSE;
      }
      return Url::fromUri($path);
    }

    $request = Request::create('/' . $path);
    $attributes = $this->getPathAttributes($path$request$access_check);

    if (!$attributes) {
      return FALSE;
    }
    if (($version !== '7')
      && ($element['#name'] == 'source_base_path' || $element['#name'] == 'source_private_file_path')) {
      return;
    }

    if ($version !== '6' && ($element['#name'] == 'd6_source_base_path')) {
      return;
    }

    if ($source = $element['#value']) {
      $msg = $this->t('Failed to read from @title.', ['@title' => $element['#title']]);
      if (UrlHelper::isExternal($source)) {
        try {
          $this->httpClient->head($source);
        }
        catch (TransferException $e) {
          $msg .= ' ' . $this->t('The server reports the following message: %error.', ['%error' => $e->getMessage()]);
          $this->errors[$element['#name']] = $msg;
        }
      }
      elseif (!file_exists($source) || (!is_dir($source)) || (!is_readable($source))) {
        $this->errors[$element['#name']] = $msg;
      }
    }
/** * Form element validation handler for matched_path elements. * * Note that #maxlength is validated by _form_validate() already. * * This checks that the submitted value matches an active route. */
  public static function validateMatchedPath(&$element, FormStateInterface $form_state, &$complete_form) {
    if (!empty($element['#value']) && ($element['#validate_path'] || $element['#convert_path'] != self::CONVERT_NONE)) {
      /** @var \Drupal\Core\Url $url */
      if ($url = \Drupal::service('path.validator')->getUrlIfValid($element['#value'])) {
        if ($url->isExternal()) {
          $form_state->setError($elementt('You cannot use an external URL, please enter a relative path.'));
          return;
        }
        if ($element['#convert_path'] == self::CONVERT_NONE) {
          // URL is valid, no conversion required.           return;
        }
        // We do the value conversion here whilst the Url object is in scope         // after validation has occurred.         if ($element['#convert_path'] == self::CONVERT_ROUTE) {
          $form_state->setValueForElement($element[
            
public static function create(ContainerInterface $container, array $configuration$plugin_id$plugin_definition) {
    return new static($configuration$plugin_id$plugin_definition$container->get('event_dispatcher')$container->get('unrouted_url_assembler'));
  }

  /** * {@inheritdoc} */
  public function execute($object = NULL) {
    $url = $this->configuration['url'];
    // Leave external URLs unchanged, and assemble others as absolute URLs     // relative to the site's base URL.     if (!UrlHelper::isExternal($url)) {
      $parts = UrlHelper::parse($url);
      // @todo '<front>' is valid input for BC reasons, may be removed by       // https://www.drupal.org/node/2421941       if ($parts['path'] === '<front>') {
        $parts['path'] = '';
      }
      $uri = 'base:' . $parts['path'];
      $options = [
        'query' => $parts['query'],
        'fragment' => $parts['fragment'],
        'absolute' => TRUE,
      ];


        // @todo Views should expect and store a leading /. See         // https://www.drupal.org/node/2423913.         $options = [
          'attributes' => [
            'class' => [
              'views-more-link',
            ],
          ],
        ];
        if (UrlHelper::isExternal($more_link_path)) {
          $more_link_url = CoreUrl::fromUri($more_link_path$options);
        }
        else {
          $more_link_url = CoreUrl::fromUserInput('/' . $more_link_path$options);
        }
        $more_link = ' ' . $this->linkGenerator()->generate($more_link_text$more_link_url);
      }
    }

    if (!empty($alter['nl2br'])) {
      $value = nl2br($value);
    }
Home | Imprint | This part of the site doesn't use cookies.