Passed
Push — master ( 595e7a...9c6cd5 )
by Timo
24:50
created

AbstractSolrService::getHost()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
1
<?php
2
namespace ApacheSolrForTypo3\Solr\System\Solr\Service;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-2017 Timo Hund <[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 3 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\PingFailedException;
28
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
29
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
30
use ApacheSolrForTypo3\Solr\System\Solr\ResponseAdapter;
31
use ApacheSolrForTypo3\Solr\Util;
32
33
use Solarium\Client;
34
use Solarium\Core\Client\Endpoint;
35
use Solarium\Core\Client\Request;
36
use Solarium\Core\Query\QueryInterface;
37
use Solarium\Exception\HttpException;
38
use TYPO3\CMS\Core\Utility\GeneralUtility;
39
40
abstract class AbstractSolrService {
41
42
    /**
43
     * @var array
44
     */
45
    protected static $pingCache = [];
46
47
    /**
48
     * @var TypoScriptConfiguration
49
     */
50
    protected $configuration;
51
52
    /**
53
     * @var \ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager
54
     */
55
    protected $logger = null;
56
57
    /**
58
     * @var Client
59
     */
60
    protected $client = null;
61
62
    /**
63
     * SolrReadService constructor.
64
     */
65 132
    public function __construct(Client $client, $typoScriptConfiguration = null, $logManager = null)
66
    {
67 132
        $this->client = $client;
68 132
        $this->configuration = $typoScriptConfiguration ?? Util::getSolrConfiguration();
69 132
        $this->logger = $logManager ?? GeneralUtility::makeInstance(SolrLogManager::class, /** @scrutinizer ignore-type */ __CLASS__);
70 132
    }
71
72
    /**
73
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getPrimaryEndpoint()->getScheme() now.
74
     * @return string
75
     */
76
    public function getScheme()
77
    {
78
        trigger_error('AbstractSolrService::getScheme is deprecated please use getPrimaryEndpoint()->getScheme() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
79
80
        $endpoint = $this->getPrimaryEndpoint();
81
        return is_null($endpoint) ? '' : $endpoint->getScheme();
82
    }
83
84
    /**
85
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getPrimaryEndpoint()->getHost() now.
86
     * @return string
87
     */
88
    public function getHost()
89
    {
90
        trigger_error('AbstractSolrService::getHost is deprecated please use getPrimaryEndpoint()->getHost() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
91
92
        $endpoint = $this->getPrimaryEndpoint();
93
        return is_null($endpoint) ? '' : $endpoint->getHost();
94
    }
95
96
    /**
97
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getPrimaryEndpoint()->getPort() now.
98
     * @return string
99
     */
100
    public function getPort()
101
    {
102
        trigger_error('AbstractSolrService::getPort is deprecated please use getPrimaryEndpoint()->getPort() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
103
104
        $endpoint = $this->getPrimaryEndpoint();
105
        return is_null($endpoint) ? '' : $endpoint->getPort();
106
    }
107
108
    /**
109
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getCorePath() now
110
     * @return string
111
     */
112
    public function getPath()
113
    {
114
        trigger_error('AbstractSolrService::getPath is deprecated please use getCorePath() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
115
116
        return $this->getCorePath();
117
    }
118
119
    /**
120
     * Returns the path to the core solr path + core path.
121
     *
122
     * @return string
123
     */
124 2
    public function getCorePath()
125
    {
126 2
        $endpoint = $this->getPrimaryEndpoint();
127 2
        return is_null($endpoint) ? '' : $endpoint->getPath() .'/'. $endpoint->getCore();
128
    }
129
130
    /**
131
     * Returns the core name from the configured path without the core name.
132
     *
133
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getPrimaryEndpoint()->getPath() now.
134
     * @return string
135
     */
136
    public function getCoreBasePath()
137
    {
138
        $endpoint = $this->getPrimaryEndpoint();
139
        return is_null($endpoint) ? '' : $endpoint->getPath();
140
    }
141
142
    /**
143
     * Returns the core name from the configured path.
144
     *
145
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getPrimaryEndpoint()->getCore() now.
146
     * @return string
147
     */
148
    public function getCoreName()
149
    {
150
        trigger_error('AbstractSolrService::getCoreName is deprecated please use getCorePath() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
151
152
        $endpoint = $this->getPrimaryEndpoint();
153
        return is_null($endpoint) ? '' : $endpoint->getCore();
154
    }
155
156
    /**
157
     * Return a valid http URL given this server's host, port and path and a provided servlet name
158
     *
159
     * @param string $servlet
160
     * @param array $params
161
     * @return string
162
     */
163 21
    protected function _constructUrl($servlet, $params = [])
164
    {
165 21
        $queryString = count($params) ? '?' . http_build_query($params, null, '&') : '';
166 21
        return $this->__toString() . $servlet . $queryString;
167
    }
168
169
    /**
170
     * Creates a string representation of the Solr connection. Specifically
171
     * will return the Solr URL.
172
     *
173
     * @return string The Solr URL.
174
     */
175 93
    public function __toString()
176
    {
177 93
        $endpoint = $this->getPrimaryEndpoint();
178 93
        if (!$endpoint instanceof Endpoint) {
179 2
            return '';
180
        }
181
182 91
        return  $endpoint->getScheme(). '://' . $endpoint->getHost() . ':' . $endpoint->getPort() . $endpoint->getPath() . '/' . $endpoint->getCore() . '/';
183
    }
184
185
    /**
186
     * @return Endpoint|null
187
     */
188 98
    public function getPrimaryEndpoint()
189
    {
190 98
        return is_array($this->client->getEndpoints()) ? reset($this->client->getEndpoints()) : null;
0 ignored issues
show
introduced by
The condition is_array($this->client->getEndpoints()) is always true.
Loading history...
191
    }
192
193
    /**
194
     * Central method for making a get operation against this Solr Server
195
     *
196
     * @param string $url
197
     * @return ResponseAdapter
198
     */
199 16
    protected function _sendRawGet($url)
200
    {
201 16
        return $this->_sendRawRequest($url, Request::METHOD_GET);
202
    }
203
204
    /**
205
     * Central method for making a HTTP DELETE operation against the Solr server
206
     *
207
     * @param string $url
208
     * @return ResponseAdapter
209
     */
210 4
    protected function _sendRawDelete($url)
211
    {
212 4
        return $this->_sendRawRequest($url, Request::METHOD_DELETE);
213
    }
214
215
    /**
216
     * Central method for making a post operation against this Solr Server
217
     *
218
     * @param string $url
219
     * @param string $rawPost
220
     * @param string $contentType
221
     * @return ResponseAdapter
222
     */
223
    protected function _sendRawPost($url, $rawPost, $contentType = 'text/xml; charset=UTF-8')
224
    {
225 4
        $initializeRequest = function(Request $request) use ($rawPost, $contentType) {
226 4
            $request->setRawData($rawPost);
227 4
            $request->addHeader('Content-Type: ' . $contentType);
228 4
            return $request;
229 4
        };
230
231 4
        return $this->_sendRawRequest($url, Request::METHOD_POST, $rawPost, $initializeRequest);
232
    }
233
234
    /**
235
     * Method that performs an http request with the solarium client.
236
     *
237
     * @param string $url
238
     * @param string $method
239
     * @param string $body
240
     * @param \Closure $initializeRequest
241
     * @return ResponseAdapter
242
     */
243 16
    protected function _sendRawRequest($url, $method = Request::METHOD_GET, $body = '', \Closure $initializeRequest = null)
244
    {
245 16
        $logSeverity = SolrLogManager::INFO;
246 16
        $exception = null;
247
248
        try {
249 16
            $request = $this->buildSolariumRequestFromUrl($url, $method);
250
251 16
            if($initializeRequest !== null) {
252 4
                $request = $initializeRequest($request);
253
            }
254
255 16
            $response = $this->executeRequest($request);
256 3
        } catch (HttpException $exception) {
257 3
            $logSeverity = SolrLogManager::ERROR;
258 3
            $response = new ResponseAdapter($exception->getBody(), $exception->getCode(), $exception->getMessage());
259
        }
260
261 16
        if ($this->configuration->getLoggingQueryRawPost() || $response->getHttpStatus() != 200) {
262 3
            $message = 'Querying Solr using '.$method;
263 3
            $this->writeLog($logSeverity, $message, $url, $response, $exception, $body);
264
        }
265
266 16
        return $response;
267
    }
268
269
    /**
270
     * Build the log data and writes the message to the log
271
     *
272
     * @param integer $logSeverity
273
     * @param string $message
274
     * @param string $url
275
     * @param ResponseAdapter $solrResponse
276
     * @param \Exception $exception
277
     * @param string $contentSend
278
     */
279 3
    protected function writeLog($logSeverity, $message, $url, $solrResponse, $exception = null, $contentSend = '')
280
    {
281 3
        $logData = $this->buildLogDataFromResponse($solrResponse, $exception, $url, $contentSend);
282 3
        $this->logger->log($logSeverity, $message, $logData);
283 3
    }
284
285
    /**
286
     * Parses the solr information to build data for the logger.
287
     *
288
     * @param ResponseAdapter $solrResponse
289
     * @param \Exception $e
290
     * @param string $url
291
     * @param string $contentSend
292
     * @return array
293
     */
294 3
    protected function buildLogDataFromResponse(ResponseAdapter $solrResponse, \Exception $e = null, $url = '', $contentSend = '')
295
    {
296 3
        $logData = ['query url' => $url, 'response' => (array)$solrResponse];
297
298 3
        if ($contentSend !== '') {
299
            $logData['content'] = $contentSend;
300
        }
301
302 3
        if (!empty($e)) {
303 3
            $logData['exception'] = $e->__toString();
304 3
            return $logData;
305
        } else {
306
            // trigger data parsing
307
            $solrResponse->response;
308
            $logData['response data'] = print_r($solrResponse, true);
309
            return $logData;
310
        }
311
    }
312
313
    /**
314
     * Call the /admin/ping servlet, can be used to quickly tell if a connection to the
315
     * server is available.
316
     *
317
     * Simply overrides the SolrPhpClient implementation, changing ping from a
318
     * HEAD to a GET request, see http://forge.typo3.org/issues/44167
319
     *
320
     * Also does not report the time, see https://forge.typo3.org/issues/64551
321
     *
322
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
323
     * @return bool TRUE if Solr can be reached, FALSE if not
324
     */
325 74
    public function ping($useCache = true)
326
    {
327
        try {
328 74
            $httpResponse = $this->performPingRequest($useCache);
329
        } catch (HttpException $exception) {
330
            return false;
331
        }
332
333 74
        return ($httpResponse->getHttpStatus() === 200);
334
    }
335
336
    /**
337
     * Call the /admin/ping servlet, can be used to get the runtime of a ping request.
338
     *
339
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
340
     * @return double runtime in milliseconds
341
     * @throws \ApacheSolrForTypo3\Solr\PingFailedException
342
     */
343 3
    public function getPingRoundTripRuntime($useCache = true)
344
    {
345
        try {
346 3
            $start = $this->getMilliseconds();
347 3
            $httpResponse = $this->performPingRequest($useCache);
348 2
            $end = $this->getMilliseconds();
349 1
        } catch (HttpException $e) {
350 1
            $message = 'Solr ping failed with unexpected response code: ' . $e->getCode();
351
            /** @var $exception \ApacheSolrForTypo3\Solr\PingFailedException */
352 1
            $exception = GeneralUtility::makeInstance(PingFailedException::class, /** @scrutinizer ignore-type */ $message);
353 1
            throw $exception;
354
        }
355
356 2
        if ($httpResponse->getHttpStatus() !== 200) {
357
            $message = 'Solr ping failed with unexpected response code: ' . $httpResponse->getHttpStatus();
358
            /** @var $exception \ApacheSolrForTypo3\Solr\PingFailedException */
359
            $exception = GeneralUtility::makeInstance(PingFailedException::class, /** @scrutinizer ignore-type */ $message);
360
            throw $exception;
361
        }
362
363 2
        return $end - $start;
364
    }
365
366
    /**
367
     * Make a request to a servlet (a path) that's not a standard path.
368
     *
369
     * @deprecated Since 9.0.0 will be removed in 10.0.0 please use getClient()->executeRequest() now
370
     * @param string $servlet Path to be added to the base Solr path.
371
     * @param array $parameters Optional, additional request parameters when constructing the URL.
372
     * @param string $method HTTP method to use, defaults to GET.
373
     * @param array $requestHeaders Key value pairs of header names and values. Should include 'Content-Type' for POST and PUT.
374
     * @param string $rawPost Must be an empty string unless method is POST or PUT.
375
     * @return ResponseAdapter Response object
376
     * @throws HttpException if returned HTTP status is other than 200
377
     */
378
    public function requestServlet($servlet, $parameters = [], $method = 'GET', $requestHeaders = [], $rawPost = '')
379
    {
380
        trigger_error('AbstractSolrService::requestServlet is deprecated please use getClient()->executeRequest() now. Will be dropped with EXT:solr 10', E_USER_DEPRECATED);
381
382
        // Add default parameters
383
        $parameters['wt'] = 'json';
384
        $url = $this->_constructUrl($servlet, $parameters);
385
386
        $setHeader = function(Request $request) use ($requestHeaders) {
387
            $request->addHeaders($requestHeaders);
388
            return $request;
389
        };
390
391
        if($method == Request::METHOD_GET) {
392
            $solrResponse = $this->_sendRawRequest($url, Request::METHOD_GET, '', $setHeader);
393
        } elseif ($method == Request::METHOD_POST) {
394
            $solrResponse = $this->_sendRawRequest($url, Request::METHOD_POST, $rawPost, $setHeader);
395
        } else {
396
            throw new \InvalidArgumentException("Invalid http method passed");
397
        }
398
399
        return $solrResponse;
400
    }
401
402
403
    /**
404
     * Performs a ping request and returns the result.
405
     *
406
     * @param boolean $useCache indicates if the ping result should be cached in the instance or not
407
     * @return ResponseAdapter
408
     */
409 77
    protected function performPingRequest($useCache = true)
410
    {
411 77
        $cacheKey = (string)($this);
412 77
        if ($useCache && isset(static::$pingCache[$cacheKey])) {
413 66
            return static::$pingCache[$cacheKey];
414
        }
415
416 77
        $pingQuery = $this->client->createPing();
417 77
        $pingResult = $this->createAndExecuteRequest($pingQuery);
418
419 76
        if ($useCache) {
420 75
            static::$pingCache[$cacheKey] = $pingResult;
421
        }
422
423 76
        return $pingResult;
424
    }
425
426
    /**
427
     * Returns the current time in milliseconds.
428
     *
429
     * @return double
430
     */
431 3
    protected function getMilliseconds()
432
    {
433 3
        return GeneralUtility::milliseconds();
434
    }
435
436
    /**
437
     * @param QueryInterface $query
438
     * @return ResponseAdapter
439
     */
440 102
    protected function createAndExecuteRequest(QueryInterface $query): ResponseAdapter
441
    {
442 102
        $request = $this->client->createRequest($query);
443 102
        return $this->executeRequest($request);
444
    }
445
446
    /**
447
     * @param $request
448
     * @return ResponseAdapter
449
     */
450 119
    protected function executeRequest($request): ResponseAdapter
451
    {
452 119
        $result = $this->client->executeRequest($request);
453 113
        return new ResponseAdapter($result->getBody(), $result->getStatusCode(), $result->getStatusMessage());
454
    }
455
456
    /**
457
     * @param string $url
458
     * @param string $httpMethod
459
     * @return Request
460
     */
461 16
    protected function buildSolariumRequestFromUrl($url, $httpMethod = Request::METHOD_GET): Request
462
    {
463 16
        $params = [];
464 16
        parse_str(parse_url($url, PHP_URL_QUERY), $params);
465
466 16
        $path = parse_url($url, PHP_URL_PATH);
467 16
        $endpoint = $this->getPrimaryEndpoint();
468 16
        $coreBasePath = $endpoint->getPath() . '/' . $endpoint->getCore() . '/';
469 16
        $handler = str_replace($coreBasePath, '', $path);
470
471 16
        $request = new Request();
472 16
        $request->setMethod($httpMethod);
473 16
        $request->setParams($params);
474 16
        $request->setHandler($handler);
475 16
        return $request;
476
    }
477
}