Passed
Pull Request — master (#1249)
by
unknown
19:13
created

PageIndexerRequest::getUrlAndDecodeResponse()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 16
cts 16
cp 1
rs 8.9713
c 0
b 0
f 0
cc 3
eloc 15
nc 2
nop 2
crap 3
1
<?php
2
namespace ApacheSolrForTypo3\Solr\IndexQueue;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2010-2015 Ingo Renner <[email protected]>
8
 *  All rights reserved
9
 *
10
 *  This script is part of the TYPO3 project. The TYPO3 project is
11
 *  free software; you can redistribute it and/or modify
12
 *  it under the terms of the GNU General Public License as published by
13
 *  the Free Software Foundation; either version 2 of the License, or
14
 *  (at your option) any later version.
15
 *
16
 *  The GNU General Public License can be found at
17
 *  http://www.gnu.org/copyleft/gpl.html.
18
 *
19
 *  This script is distributed in the hope that it will be useful,
20
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 *  GNU General Public License for more details.
23
 *
24
 *  This copyright notice MUST APPEAR in all copies of the script!
25
 ***************************************************************/
26
27
use ApacheSolrForTypo3\Solr\System\Configuration\ExtensionConfiguration;
28
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
29
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
31
/**
32
 * Index Queue Page Indexer request with details about which actions to perform.
33
 *
34
 * @author Ingo Renner <[email protected]>
35
 */
36
class PageIndexerRequest
37
{
38
39
    /**
40
     * List of actions to perform during page rendering.
41
     *
42
     * @var array
43
     */
44
    protected $actions = [];
45
46
    /**
47
     * Parameters as sent from the Index Queue page indexer.
48
     *
49
     * @var array
50
     */
51
    protected $parameters = [];
52
53
    /**
54
     * Headers as sent from the Index Queue page indexer.
55
     *
56
     * @var array
57
     */
58
    protected $header = [];
59
60
    /**
61
     * Unique request ID.
62
     *
63
     * @var string
64
     */
65
    protected $requestId;
66
67
    /**
68
     * Username to use for basic auth protected URLs.
69
     *
70
     * @var string
71
     */
72
    protected $username = '';
73
74
    /**
75
     * Password to use for basic auth protected URLs.
76
     *
77
     * @var string
78
     */
79
    protected $password = '';
80
81
    /**
82
     * An Index Queue item related to this request.
83
     *
84
     * @var Item
85
     */
86
    protected $indexQueueItem = null;
87
88
    /**
89
     * Request timeout in seconds
90
     *
91
     * @var float
92
     */
93
    protected $timeout;
94
95
    /**
96
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
97
     */
98
    protected $logger = null;
99
100
    /**
101
     * @var ExtensionConfiguration
102
     */
103
    protected $extensionConfiguration;
104
105
    /**
106
     * PageIndexerRequest constructor.
107
     *
108
     * @param string $jsonEncodedParameters json encoded header
109
     */
110 17
    public function __construct($jsonEncodedParameters = null)
111
    {
112 17
        $this->logger = GeneralUtility::makeInstance(SolrLogManager::class, __CLASS__);
113 17
        $this->requestId = uniqid();
114 17
        $this->timeout = (float)ini_get('default_socket_timeout');
115 17
        $this->extensionConfiguration = GeneralUtility::makeInstance(ExtensionConfiguration::class);
116
117 17
        if (is_null($jsonEncodedParameters)) {
118 10
            return;
119
        }
120
121 7
        $this->parameters = (array)json_decode($jsonEncodedParameters, true);
122 7
        $this->requestId = $this->parameters['requestId'];
123 7
        unset($this->parameters['requestId']);
124
125 7
        $actions = explode(',', $this->parameters['actions']);
126 7
        foreach ($actions as $action) {
127 7
            $this->addAction($action);
128 7
        }
129 7
        unset($this->parameters['actions']);
130 7
    }
131
132
    /**
133
     * Adds an action to perform during page rendering.
134
     *
135
     * @param string $action Action name.
136
     */
137 8
    public function addAction($action)
138
    {
139 8
        $this->actions[] = $action;
140 8
    }
141
142
    /**
143
     * Executes the request.
144
     *
145
     * Uses headers to submit additional data and avoiding to have these
146
     * arguments integrated into the URL when created by RealURL.
147
     *
148
     * @param string $url The URL to request.
149
     * @return PageIndexerResponse Response
150
     */
151 5
    public function send($url)
152
    {
153
        /** @var $response PageIndexerResponse */
154 5
        $response = GeneralUtility::makeInstance(PageIndexerResponse::class);
155 5
        $decodedResponse = $this->getUrlAndDecodeResponse($url, $response);
156
157 4
        if ($decodedResponse['requestId'] != $this->requestId) {
158 1
            throw new \RuntimeException(
159 1
                'Request ID mismatch. Request ID was ' . $this->requestId . ', received ' . $decodedResponse['requestId'] . '. Are requests cached?',
160
                1351260655
161 1
            );
162
        }
163
164 3
        $response->setRequestId($decodedResponse['requestId']);
165
166 3
        if (!is_array($decodedResponse['actionResults'])) {
167
            // nothing to parse
168
            return $response;
169
        }
170
171 3
        foreach ($decodedResponse['actionResults'] as $action => $actionResult) {
172 3
            $response->addActionResult($action, $actionResult);
173 3
        }
174
175 3
        return $response;
176
    }
177
178
    /**
179
     * This method is used to retrieve an url from the frontend and decode the response.
180
     *
181
     * @param string $url
182
     * @param PageIndexerResponse $response
183
     * @return mixed
184
     */
185 5
    protected function getUrlAndDecodeResponse($url, PageIndexerResponse $response)
186
    {
187 5
        $headers = $this->getHeaders();
188 5
        $rawResponse = $this->getUrl($url, $headers, $this->timeout);
189
        // convert JSON response to response object properties
190 5
        $decodedResponse = $response->getResultsFromJson($rawResponse);
191
192 5
        if ($rawResponse === false || $decodedResponse === false) {
193 1
            $this->logger->log(
194 1
                SolrLogManager::ERROR,
195 1
                'Failed to execute Page Indexer Request. Request ID: ' . $this->requestId,
196
                [
197 1
                    'request ID' => $this->requestId,
198 1
                    'request url' => $url,
199 1
                    'request headers' => $headers,
200 1
                    'response headers' => $http_response_header, // automatically defined by file_get_contents()
201
                    'raw response body' => $rawResponse
202 1
                ]
203 1
            );
204
205 1
            throw new \RuntimeException('Failed to execute Page Indexer Request. See log for details. Request ID: ' . $this->requestId, 1319116885);
206
        }
207 4
        return $decodedResponse;
208
    }
209
210
    /**
211
     * Generates the headers to be send with the request.
212
     *
213
     * @return string[] Array of HTTP headers.
214
     */
215 6
    public function getHeaders()
216
    {
217 6
        $headers = $this->header;
218 6
        $headers[] = TYPO3_user_agent;
219 6
        $itemId = $this->indexQueueItem->getIndexQueueUid();
220 6
        $pageId = $this->indexQueueItem->getRecordPageId();
221
222
        $indexerRequestData = [
223 6
            'requestId' => $this->requestId,
224 6
            'item' => $itemId,
225 6
            'page' => $pageId,
226 6
            'actions' => implode(',', $this->actions),
227 6
            'hash' => md5(
228 6
                $itemId . '|' .
229 6
                $pageId . '|' .
230 6
                $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
231 6
            )
232 6
        ];
233
234 6
        $indexerRequestData = array_merge($indexerRequestData, $this->parameters);
235 6
        $headers[] = 'X-Tx-Solr-Iq: ' . json_encode($indexerRequestData);
236
237 6
        if (!empty($this->username) && !empty($this->password)) {
238 1
            $headers[] = 'Authorization: Basic ' . base64_encode($this->username . ':' . $this->password);
239 1
        }
240
241 6
        return $headers;
242
    }
243
244
    /**
245
     * Adds an HTTP header to be send with the request.
246
     *
247
     * @param string $header HTTP header
248
     */
249
    public function addHeader($header)
250
    {
251
        $this->header[] = $header;
252
    }
253
254
    /**
255
     * Checks whether this is a legitimate request coming from the Index Queue
256
     * page indexer worker task.
257
     *
258
     * @return bool TRUE if it's a legitimate request, FALSE otherwise.
259
     */
260 2
    public function isAuthenticated()
261
    {
262 2
        $authenticated = false;
263
264 2
        if (is_null($this->parameters)) {
265
            return $authenticated;
266
        }
267
268 2
        $calculatedHash = md5(
269 2
            $this->parameters['item'] . '|' .
270 2
            $this->parameters['page'] . '|' .
271 2
            $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']
272 2
        );
273
274 2
        if ($this->parameters['hash'] === $calculatedHash) {
275 1
            $authenticated = true;
276 1
        }
277
278 2
        return $authenticated;
279
    }
280
281
    /**
282
     * Gets the list of actions to perform during page rendering.
283
     *
284
     * @return array List of actions
285
     */
286
    public function getActions()
287
    {
288
        return $this->actions;
289
    }
290
291
    /**
292
     * Gets the request's parameters.
293
     *
294
     * @return array Request parameters.
295
     */
296
    public function getParameters()
297
    {
298
        return $this->parameters;
299
    }
300
301
    /**
302
     * Gets the request's unique ID.
303
     *
304
     * @return string Unique request ID.
305
     */
306 1
    public function getRequestId()
307
    {
308 1
        return $this->requestId;
309
    }
310
311
    /**
312
     * Gets a specific parameter's value.
313
     *
314
     * @param string $parameterName The parameter to retrieve.
315
     * @return mixed NULL if a parameter was not set or it's value otherwise.
316
     */
317 7
    public function getParameter($parameterName)
318
    {
319 7
        return isset($this->parameters[$parameterName]) ? $this->parameters[$parameterName] : null;
320
    }
321
322
    /**
323
     * Sets a request's parameter and its value.
324
     *
325
     * @param string $parameter Parameter name
326
     * @param mixed $value Parameter value.
327
     */
328 8
    public function setParameter($parameter, $value)
329
    {
330 8
        if (is_bool($value)) {
331 1
            $value = $value ? '1' : '0';
332 1
        }
333
334 8
        $this->parameters[$parameter] = $value;
335 8
    }
336
337
    /**
338
     * Sets username and password to be used for a basic auth request header.
339
     *
340
     * @param string $username username.
341
     * @param string $password password.
342
     */
343 1
    public function setAuthorizationCredentials($username, $password)
344
    {
345 1
        $this->username = $username;
346 1
        $this->password = $password;
347 1
    }
348
349
    /**
350
     * Sets the Index Queue item this request is related to.
351
     *
352
     * @param Item $item Related Index Queue item.
353
     */
354 6
    public function setIndexQueueItem(Item $item)
355
    {
356 6
        $this->indexQueueItem = $item;
357 6
    }
358
359
    /**
360
     * Returns the request timeout in seconds
361
     *
362
     * @return float
363
     */
364 1
    public function getTimeout()
365
    {
366 1
        return $this->timeout;
367
    }
368
369
    /**
370
     * Sets the request timeout in seconds
371
     *
372
     * @param float $timeout Timeout seconds
373
     */
374
    public function setTimeout($timeout)
375
    {
376
        $this->timeout = (float)$timeout;
377
    }
378
379
    /**
380
     * Fetches a page by sending the configured headers.
381
     *
382
     * @param string $url
383
     * @param string[] $headers
384
     * @param float $timeout
385
     * @return string
386
     */
387 1
    protected function getUrl($url, $headers, $timeout)
388
    {
389
        $options = [
390
            'http' => [
391 1
                'header' => implode(CRLF, $headers),
392
                'timeout' => $timeout
393 1
            ],
394 1
        ];
395
396 1
        if ($this->extensionConfiguration->getIsSelfSignedCertificatesEnabled()) {
397
            $options['ssl'] = [
398
                'verify_peer' => false,
399
                'allow_self_signed'=> true
400
            ];
401
        }
402
403 1
        $context = stream_context_create($options);
404 1
        $rawResponse = file_get_contents($url, false, $context);
405 1
        return $rawResponse;
406
    }
407
}
408