You are here

protected function DuplicateContentPreventionMiddleware::getRedirectUrl in CDN 8.3

Determines whether a redirect should be performed for the current request.

Parameters

\Symfony\Component\HttpFoundation\Request $request: The current request.

Return value

bool|string FALSE if no redirect should occur, or the absolute URL to redirect to.

1 call to DuplicateContentPreventionMiddleware::getRedirectUrl()
DuplicateContentPreventionMiddleware::handle in src/StackMiddleware/DuplicateContentPreventionMiddleware.php
Handles a Request to convert it to a Response.

File

src/StackMiddleware/DuplicateContentPreventionMiddleware.php, line 142

Class

DuplicateContentPreventionMiddleware
Redirects CDN user agents' requests for HTML to the canonical location.

Namespace

Drupal\cdn\StackMiddleware

Code

protected function getRedirectUrl(Request $request) {
  $path = $request
    ->getPathInfo();

  // If the path ends in an extension that is not in the list of forbidden
  // extensions, then return FALSE to indicate that no redirect should occur.
  // We cannot assume that this can only happen inside the /sites directory,
  // because a Drupal 8 site can choose to use a different directory for
  // generated files. We use a blacklist rather than a whitelist of extensions
  // to ensure that any current and future files can be served.
  $extension = mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));
  if (!in_array($extension, $this->forbiddenExtensions)) {
    return FALSE;
  }
  assert(Inspector::assertAllStrings($this->cdnOnlyRequestHeaders), 'CDN-only request headers must be strings.');
  foreach ($this->cdnOnlyRequestHeaders as $cdn_only_request_header) {
    if ($request->headers
      ->has($cdn_only_request_header)) {
      return $this
        ->generateRedirectUrl($request);
    }
  }

  // Use case-insensitive substring matching to match the current User-Agent
  // to the list of CDN user agents.
  if ($request->headers
    ->has('User-Agent')) {
    $ua = mb_strtolower($request->headers
      ->get('User-Agent'));
    assert(Inspector::assertAllStrings($this->cdnUserAgents), 'CDN user agents must be strings.');
    assert(Inspector::assertAll(function ($s) {
      return mb_strtolower($s) === $s;
    }, $this->cdnUserAgents), 'CDN user agents must be lower case strings.');

    // @codingStandardsIgnoreLine
    foreach ($this->cdnUserAgents as $cdn_ua) {
      if (strstr($ua, $cdn_ua)) {
        return $this
          ->generateRedirectUrl($request);
      }
    }
  }
  return FALSE;
}