Completed
Push — master ( 324c2f...3e3e29 )
by Timo
47s
created

Search::getResultsPerPage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
namespace ApacheSolrForTypo3\Solr;
3
4
/***************************************************************
5
 *  Copyright notice
6
 *
7
 *  (c) 2009-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\ConnectionManager;
28
use ApacheSolrForTypo3\Solr\Query\Modifier\Modifier;
29
use ApacheSolrForTypo3\Solr\Search\FacetsModifier;
30
use ApacheSolrForTypo3\Solr\Search\ResponseModifier;
31
use ApacheSolrForTypo3\Solr\Search\SearchAware;
32
use ApacheSolrForTypo3\Solr\System\Configuration\TypoScriptConfiguration;
33
use TYPO3\CMS\Core\SingletonInterface;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
36
/**
37
 * Class to handle solr search requests
38
 *
39
 * @author Ingo Renner <[email protected]>
40
 */
41
class Search implements SingletonInterface
42
{
43
44
    /**
45
     * An instance of the Solr service
46
     *
47
     * @var SolrService
48
     */
49
    protected $solr = null;
50
51
    /**
52
     * The search query
53
     *
54
     * @var Query
55
     */
56
    protected $query = null;
57
58
    /**
59
     * The search response
60
     *
61
     * @var \Apache_Solr_Response
62
     */
63
    protected $response = null;
64
65
    /**
66
     * Flag for marking a search
67
     *
68
     * @var bool
69
     */
70
    protected $hasSearched = false;
71
72
    /**
73
     * @var TypoScriptConfiguration
74
     */
75
    protected $configuration;
76
77
    // TODO Override __clone to reset $response and $hasSearched
78
79
    /**
80
     * Constructor
81
     *
82
     * @param SolrService $solrConnection The Solr connection to use for searching
83
     */
84 48
    public function __construct(SolrService $solrConnection = null)
85
    {
86 48
        $this->solr = $solrConnection;
87
88 48
        if (is_null($solrConnection)) {
89
            /** @var $connectionManager ConnectionManager */
90 1
            $connectionManager = GeneralUtility::makeInstance(ConnectionManager::class);
91 1
            $this->solr = $connectionManager->getConnectionByPageId($GLOBALS['TSFE']->id, $GLOBALS['TSFE']->sys_language_uid);
92
        }
93
94 48
        $this->configuration = Util::getSolrConfiguration();
95 48
    }
96
97
    /**
98
     * Gets the Solr connection used by this search.
99
     *
100
     * @return SolrService Solr connection
101
     */
102
    public function getSolrConnection()
103
    {
104
        return $this->solr;
105
    }
106
107
    /**
108
     * Sets the Solr connection used by this search.
109
     *
110
     * Since ApacheSolrForTypo3\Solr\Search is a \TYPO3\CMS\Core\SingletonInterface, this is needed to
111
     * be able to switch between multiple cores/connections during
112
     * one request
113
     *
114
     * @param SolrService $solrConnection
115
     */
116
    public function setSolrConnection(SolrService $solrConnection)
117
    {
118
        $this->solr = $solrConnection;
119
    }
120
121
    /**
122
     * Executes a query against a Solr server.
123
     *
124
     * 1) Gets the query string
125
     * 2) Conducts the actual search
126
     * 3) Checks debug settings
127
     *
128
     * @param Query $query The query with keywords, filters, and so on.
129
     * @param int $offset Result offset for pagination.
130
     * @param int $limit Maximum number of results to return. If set to NULL, this value is taken from the query object.
131
     * @return \Apache_Solr_Response Solr response
132
     */
133 25
    public function search(Query $query, $offset = 0, $limit = 10)
134
    {
135 25
        $query = $this->modifyQuery($query);
136 25
        $this->query = $query;
137
138 25
        if (empty($limit)) {
139 23
            $limit = $query->getResultsPerPage();
140
        }
141
142
        try {
143 25
            $response = $this->solr->search(
144 25
                $query->getQueryString(),
145
                $offset,
146
                $limit,
147 25
                $query->getQueryParameters()
148
            );
149
150 25
            if ($this->configuration->getLoggingQueryQueryString()) {
151
                GeneralUtility::devLog('Querying Solr, getting result', 'solr',
152
                    0, array(
153
                        'query string' => $query->getQueryString(),
154
                        'query parameters' => $query->getQueryParameters(),
155
                        'response' => json_decode($response->getRawResponse(),
156 25
                            true)
157
                    ));
158
            }
159
        } catch (\RuntimeException $e) {
160
            $response = $this->solr->getResponse();
161
162
            if ($this->configuration->getLoggingExceptions()) {
163
                GeneralUtility::devLog('Exception while querying Solr', 'solr',
164
                    3, array(
165
                        'exception' => $e->__toString(),
166
                        'query' => (array)$query,
167
                        'offset' => $offset,
168
                        'limit' => $limit
169
                    ));
170
            }
171
        }
172
173 25
        $response = $this->modifyResponse($response);
174 25
        $this->response = $response;
175 25
        $this->hasSearched = true;
176
177 25
        return $this->response;
178
    }
179
180
    /**
181
     * Allows to modify a query before eventually handing it over to Solr.
182
     *
183
     * @param Query $query The current query before it's being handed over to Solr.
184
     * @return Query The modified query that is actually going to be given to Solr.
185
     */
186 25
    protected function modifyQuery(Query $query)
187
    {
188
        // hook to modify the search query
189 25
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchQuery'])) {
190 23
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchQuery'] as $classReference) {
191 23
                $queryModifier = GeneralUtility::getUserObj($classReference);
192
193 23
                if ($queryModifier instanceof Modifier) {
194 23
                    if ($queryModifier instanceof SearchAware) {
195
                        $queryModifier->setSearch($this);
196
                    }
197
198 23
                    $query = $queryModifier->modifyQuery($query);
199
                } else {
200
                    throw new \UnexpectedValueException(
201
                        get_class($queryModifier) . ' must implement interface ApacheSolrForTypo3\Solr\Query\Modifier\QueryModifier',
202 23
                        1310387414
203
                    );
204
                }
205
            }
206
        }
207
208 25
        return $query;
209
    }
210
211
    /**
212
     * Allows to modify a response returned from Solr before returning it to
213
     * the rest of the extension.
214
     *
215
     * @param \Apache_Solr_Response $response The response as returned by Solr
216
     * @return \Apache_Solr_Response The modified response that is actually going to be returned to the extension.
217
     * @throws \UnexpectedValueException if a response modifier does not implement interface ApacheSolrForTypo3\Solr\Search\ResponseModifier
218
     */
219 25
    protected function modifyResponse(\Apache_Solr_Response $response)
220
    {
221
        // hook to modify the search response
222 25
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchResponse'])) {
223
            foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifySearchResponse'] as $classReference) {
224
                $responseModifier = GeneralUtility::getUserObj($classReference);
225
226
                if ($responseModifier instanceof ResponseModifier) {
227
                    if ($responseModifier instanceof SearchAware) {
228
                        $responseModifier->setSearch($this);
229
                    }
230
231
                    $response = $responseModifier->modifyResponse($response);
232
                } else {
233
                    throw new \UnexpectedValueException(
234
                        get_class($responseModifier) . ' must implement interface ApacheSolrForTypo3\Solr\Search\ResponseModifier',
235
                        1343147211
236
                    );
237
                }
238
            }
239
240
            // add modification indicator
241
            $response->response->isModified = true;
242
        }
243
244 25
        return $response;
245
    }
246
247
    /**
248
     * Sends a ping to the solr server to see whether it is available.
249
     *
250
     * @param bool $useCache Set to true if the cache should be used.
251
     * @return bool Returns TRUE on successful ping.
252
     * @throws \Exception Throws an exception in case ping was not successful.
253
     */
254 25
    public function ping($useCache = true)
255
    {
256 25
        $solrAvailable = false;
257
258
        try {
259 25
            if (!$this->solr->ping(2, $useCache)) {
260
                throw new \Exception('Solr Server not responding.', 1237475791);
261
            }
262
263 25
            $solrAvailable = true;
264
        } catch (\Exception $e) {
265
            if ($this->configuration->getLoggingExceptions()) {
266
                GeneralUtility::devLog('exception while trying to ping the solr server',
267
                    'solr', 3, array(
268
                        $e->__toString()
269
                    ));
270
            }
271
        }
272
273 25
        return $solrAvailable;
274
    }
275
276
    /**
277
     * checks whether a search has been executed
278
     *
279
     * @return bool    TRUE if there was a search, FALSE otherwise (if the user just visited the search page f.e.)
280
     */
281 25
    public function hasSearched()
282
    {
283 25
        return $this->hasSearched;
284
    }
285
286
    /**
287
     * Gets the query object.
288
     *
289
     * @return Query Query
290
     */
291 28
    public function getQuery()
292
    {
293 28
        return $this->query;
294
    }
295
296
    /**
297
     * Gets the Solr response
298
     *
299
     * @return \Apache_Solr_Response
300
     */
301 18
    public function getResponse()
302
    {
303 18
        return $this->response;
304
    }
305
306
    public function getRawResponse()
307
    {
308
        return $this->response->getRawResponse();
309
    }
310
311 18
    public function getResponseHeader()
312
    {
313 18
        return $this->getResponse()->responseHeader;
314
    }
315
316 18
    public function getResponseBody()
317
    {
318 18
        return $this->getResponse()->response;
319
    }
320
321
    /**
322
     * Returns all results documents raw. Use with caution!
323
     *
324
     * @return \Apache_Solr_Document[]
325
     */
326
    public function getResultDocumentsRaw()
327
    {
328
        return $this->getResponseBody()->docs;
329
    }
330
331
    /**
332
     * Returns all result documents but applies htmlspecialchars() on all fields retrieved
333
     * from solr except the configured fields in plugin.tx_solr.search.trustedFields
334
     *
335
     * @return \Apache_Solr_Document[]
336
     */
337 18
    public function getResultDocumentsEscaped()
338
    {
339 18
        return $this->applyHtmlSpecialCharsOnAllFields($this->getResponseBody()->docs);
340
    }
341
342
    /**
343
     * This method is used to apply htmlspecialchars on all document fields that
344
     * are not configured to be secure. Secure mean that we know where the content is coming from.
345
     *
346
     * @param array $documents
347
     * @return \Apache_Solr_Document[]
348
     */
349 18
    protected function applyHtmlSpecialCharsOnAllFields(array $documents)
350
    {
351 18
        $trustedSolrFields = $this->configuration->getSearchTrustedFieldsArray();
352
353 18
        foreach ($documents as $key => $document) {
354 18
            $fieldNames = $document->getFieldNames();
355
356 18
            foreach ($fieldNames as $fieldName) {
357 18
                if (in_array($fieldName, $trustedSolrFields)) {
358
                    // we skip this field, since it was marked as secure
359 18
                    continue;
360
                }
361
362 18
                $document->{$fieldName} = $this->applyHtmlSpecialCharsOnSingleFieldValue($document->{$fieldName});
363
            }
364
365 18
            $documents[$key] = $document;
366
        }
367
368 18
        return $documents;
369
    }
370
371
    /**
372
     * Applies htmlspecialchars on all items of an array of a single value.
373
     *
374
     * @param $fieldValue
375
     * @return array|string
376
     */
377 18
    protected function applyHtmlSpecialCharsOnSingleFieldValue($fieldValue)
378
    {
379 18
        if (is_array($fieldValue)) {
380 17
            foreach ($fieldValue as $key => $fieldValueItem) {
381 17
                $fieldValue[$key] = htmlspecialchars($fieldValueItem, null, null, false);
382
            }
383
        } else {
384 18
            $fieldValue = htmlspecialchars($fieldValue, null, null, false);
385
        }
386
387 18
        return $fieldValue;
388
    }
389
390
    /**
391
     * Gets the time Solr took to execute the query and return the result.
392
     *
393
     * @return int Query time in milliseconds
394
     */
395 18
    public function getQueryTime()
396
    {
397 18
        return $this->getResponseHeader()->QTime;
398
    }
399
400
    /**
401
     * Gets the number of results per page.
402
     *
403
     * @return int Number of results per page
404
     */
405
    public function getResultsPerPage()
406
    {
407
        return $this->getResponseHeader()->params->rows;
408
    }
409
410
    /**
411
     * Gets all facets with their fields, options, and counts.
412
     *
413
     * @return array
414
     */
415 18
    public function getFacetCounts()
416
    {
417 18
        static $facetCountsModified = false;
418 18
        static $facetCounts = null;
419
420 18
        $unmodifiedFacetCounts = $this->response->facet_counts;
421
422 18
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifyFacets'])) {
423
            if (!$facetCountsModified) {
424
                $facetCounts = $unmodifiedFacetCounts;
425
426
                foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['modifyFacets'] as $classReference) {
427
                    $facetsModifier = GeneralUtility::getUserObj($classReference);
428
429
                    if ($facetsModifier instanceof FacetsModifier) {
430
                        $facetCounts = $facetsModifier->modifyFacets($facetCounts);
431
                        $facetCountsModified = true;
432
                    } else {
433
                        throw new \UnexpectedValueException(
434
                            get_class($facetsModifier) . ' must implement interface ApacheSolrForTypo3\Solr\Facet\FacetsModifier',
435
                            1310387526
436
                        );
437
                    }
438
                }
439
            }
440
        } else {
441 18
            $facetCounts = $unmodifiedFacetCounts;
442
        }
443
444 18
        return $facetCounts;
445
    }
446
447 18
    public function getFacetFieldOptions($facetField)
448
    {
449 18
        $facetOptions = null;
450
451 18
        if (property_exists($this->getFacetCounts()->facet_fields,
452
            $facetField)) {
453 18
            $facetOptions = get_object_vars($this->getFacetCounts()->facet_fields->$facetField);
454
        }
455
456 18
        return $facetOptions;
457
    }
458
459
    public function getFacetQueryOptions($facetField)
460
    {
461
        $options = array();
462
463
        $facetQueries = get_object_vars($this->getFacetCounts()->facet_queries);
464
        foreach ($facetQueries as $facetQuery => $numberOfResults) {
465
            // remove tags from the facet.query response, for facet.field
466
            // and facet.range Solr does that on its own automatically
467
            $facetQuery = preg_replace('/^\{!ex=[^\}]*\}(.*)/', '\\1',
468
                $facetQuery);
469
470
            if (GeneralUtility::isFirstPartOfStr($facetQuery, $facetField)) {
471
                $options[$facetQuery] = $numberOfResults;
472
            }
473
        }
474
475
        // filter out queries with no results
476
        $options = array_filter($options);
477
478
        return $options;
479
    }
480
481
    public function getFacetRangeOptions($rangeFacetField)
482
    {
483
        return get_object_vars($this->getFacetCounts()->facet_ranges->$rangeFacetField);
484
    }
485
486 20
    public function getNumberOfResults()
487
    {
488 20
        return $this->response->response->numFound;
489
    }
490
491
    /**
492
     * Gets the result offset.
493
     *
494
     * @return int Result offset
495
     */
496 18
    public function getResultOffset()
497
    {
498 18
        return $this->response->response->start;
499
    }
500
501 27
    public function getMaximumResultScore()
502
    {
503 27
        return $this->response->response->maxScore;
504
    }
505
506
    public function getDebugResponse()
507
    {
508
        return $this->response->debug;
509
    }
510
511 18
    public function getHighlightedContent()
512
    {
513 18
        $highlightedContent = false;
514
515 18
        if ($this->response->highlighting) {
516 18
            $highlightedContent = $this->response->highlighting;
517
        }
518
519 18
        return $highlightedContent;
520
    }
521
522 20
    public function getSpellcheckingSuggestions()
523
    {
524 20
        $spellcheckingSuggestions = false;
525
526 20
        $suggestions = (array)$this->response->spellcheck->suggestions;
527
528 20
        if (!empty($suggestions)) {
529 5
            $spellcheckingSuggestions = $suggestions;
530
531 5
            if (isset($this->response->spellcheck->collations)) {
532 5
                $collections = (array) $this->response->spellcheck->collations;
533 5
                $spellcheckingSuggestions['collation'] = $collections['collation'];
534
            }
535
        }
536
537 20
        return $spellcheckingSuggestions;
538
    }
539
}
540