You are here

public function Domain301RedirectManager::checkRedirectLoop in Domain 301 Redirect 8

Determine if connection should be refreshed.

Parameters

string $domain: The domain to be checked.

Return value

array Returns the list of options that domain_301_redirect provides.

Overrides Domain301RedirectManagerInterface::checkRedirectLoop

File

src/Domain301RedirectManager.php, line 99

Class

Domain301RedirectManager
Defines an Domain301RedirectManager service.

Namespace

Drupal\domain_301_redirect

Code

public function checkRedirectLoop($domain, &$redirect_count = 0) {

  // Get host from configured domain.
  $host = $this->request
    ->getHost();
  $scheme = $this->request
    ->getScheme();
  $parsed_url = parse_url($domain);
  $redirect_host = mb_strtolower($parsed_url['host']);
  $redirect_scheme = $parsed_url['scheme'] ?? 'http';

  // Redirecting back to this site actually is actively ignored in hook_init,
  // so it makes no sense to allow users to set this as a value. On the other
  // hand when the admin is on the redirected domain he should still be able
  // to alter other settings without first disabling redirection. So let's
  // just accept the current host.
  if ($redirect_host == $host && $scheme == $redirect_scheme) {
    return FALSE;
  }
  $redirect_loop = FALSE;
  $loop_max_redirects = $this->config
    ->get('loop_max_redirects');
  $client = $this->client;
  try {
    $response = $client
      ->request('HEAD', $domain, [
      'allow_redirects' => [
        'track_redirects' => TRUE,
        'max' => $loop_max_redirects,
      ],
    ]);
  } catch (GuzzleException $e) {
    return FALSE;
  }

  // Check the redirect history for this domain. If it is found then
  // a redirect loop is present.
  $redirect_history = $response
    ->getHeaderLine('X-Guzzle-Redirect-History');
  $redirects_urls = $redirect_history ? explode(', ', $redirect_history) : [];

  // Set the number of redirects as any redirects are probably undesirable.
  $redirect_count = count($redirects_urls);
  foreach ($redirects_urls as $redirect_url) {
    $parsed_url = parse_url($redirect_url);
    $redirect_url_host = mb_strtolower($parsed_url['host']);
    $redirect_url_scheme = $parsed_url['scheme'] ?? 'http';
    if ($redirect_url_host == $host && $redirect_url_scheme == $scheme) {
      $redirect_loop = TRUE;
      break;
    }
  }
  return $redirect_loop;
}