You are here

public function SearchSubscriber::preExecuteRequest in Acquia Search 3.x

Same name and namespace in other branches
  1. 2.x src/EventSubscriber/SearchSubscriber.php \Drupal\acquia_search\EventSubscriber\SearchSubscriber::preExecuteRequest()

Build Acquia Search Solr Authenticator.

Parameters

\Solarium\Core\Event\PreExecuteRequest $event: PreExecuteRequest event.

File

src/EventSubscriber/SearchSubscriber.php, line 73

Class

SearchSubscriber
Class SearchSubscriber.

Namespace

Drupal\acquia_search\EventSubscriber

Code

public function preExecuteRequest(PreExecuteRequest $event) {

  /** @var \Solarium\Core\Client\Request $request */
  $request = $event
    ->getRequest();
  if (!$this->client instanceof Client) {
    return;
  }

  // Run Flood control checks.
  if (!Flood::isAllowed($request
    ->getHandler())) {

    // If request should be blocked, show an error message.
    $message = 'The Acquia Search flood control mechanism has blocked a Solr query due to API usage limits. You should retry in a few seconds. Contact the site administrator if this message persists.';
    \Drupal::messenger()
      ->addError($message);

    // Build a static response which avoids a network request to Solr.
    $response = new Response($message, [
      'HTTP/1.1 429 Too Many Requests',
    ]);
    $event
      ->setResponse($response);
    $event
      ->stopPropagation();
    return;
  }
  $request
    ->addParam('request_id', uniqid(), TRUE);
  if ($request
    ->getFileUpload()) {
    $helper = new AdapterHelper();
    $body = $helper
      ->buildUploadBodyFromRequest($request);
    $request
      ->setRawData($body);
  }

  // If we're hosted on Acquia, and have an Acquia request ID,
  // append it to the request so that we map Solr queries to Acquia search
  // requests.
  if (isset($_ENV['HTTP_X_REQUEST_ID'])) {
    $xid = empty($_ENV['HTTP_X_REQUEST_ID']) ? '-' : $_ENV['HTTP_X_REQUEST_ID'];
    $request
      ->addParam('x-request-id', $xid, TRUE);
  }
  $endpoint = $this->client
    ->getEndpoint();
  $this->uri = AdapterHelper::buildUri($request, $endpoint);
  $this->nonce = Crypt::randomBytesBase64(24);
  $raw_post_data = $request
    ->getRawData();

  // We don't have any raw POST data for pings only.
  if (!$raw_post_data) {
    $parsed_url = parse_url($this->uri);
    $path = $parsed_url['path'] ?? '/';
    $query = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
    $raw_post_data = $path . $query;
  }
  $cookie = $this
    ->calculateAuthCookie($raw_post_data, $this->nonce);
  $request
    ->addHeader('Cookie: ' . $cookie);
  $request
    ->addHeader('User-Agent: ' . 'acquia_search/' . Storage::getVersion());
}