/
Params.php
740 lines (678 loc) · 22.7 KB
/
Params.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
<?php
/**
* Solr aspect of the Search Multi-class (Params)
*
* PHP version 8
*
* Copyright (C) Villanova University 2011.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Search_Solr
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Search\Solr;
use VuFindSearch\ParamBag;
use function count;
use function in_array;
use function is_array;
/**
* Solr Search Parameters
*
* @category VuFind
* @package Search_Solr
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class Params extends \VuFind\Search\Base\Params
{
use \VuFind\Search\Params\FacetLimitTrait;
use \VuFind\Search\Params\FacetRestrictionsTrait;
/**
* Search with facet.contains
* cf. https://lucene.apache.org/solr/guide/7_3/faceting.html
*
* @var string
*/
protected $facetContains = null;
/**
* Ignore Case when using facet.contains
* cf. https://lucene.apache.org/solr/guide/7_3/faceting.html
*
* @var bool
*/
protected $facetContainsIgnoreCase = null;
/**
* Offset for facet results
*
* @var int
*/
protected $facetOffset = null;
/**
* Prefix for facet searching
*
* @var string
*/
protected $facetPrefix = null;
/**
* Sorting order for facet search results
*
* @var string
*/
protected $facetSort = null;
/**
* Sorting order of single facet by index
*
* @var array
*/
protected $indexSortedFacets = null;
/**
* Fields for visual faceting
*
* @var string
*/
protected $pivotFacets = null;
/**
* Hierarchical Facet Helper
*
* @var HierarchicalFacetHelper
*/
protected $facetHelper;
/**
* Are we searching by ID only (instead of a normal query)?
*
* @var bool
*/
protected $searchingById = false;
/**
* Config sections to search for facet labels if no override configuration
* is set.
*
* @var array
*/
protected $defaultFacetLabelSections
= ['Advanced', 'HomePage', 'ResultsTop', 'Results', 'ExtraFacetLabels'];
/**
* Config sections to search for checkbox facet labels if no override
* configuration is set.
*
* @var array
*/
protected $defaultFacetLabelCheckboxSections = ['CheckboxFacets'];
/**
* Constructor
*
* @param \VuFind\Search\Base\Options $options Options to use
* @param \VuFind\Config\PluginManager $configLoader Config loader
* @param HierarchicalFacetHelper $facetHelper Hierarchical facet helper
*/
public function __construct(
$options,
\VuFind\Config\PluginManager $configLoader,
HierarchicalFacetHelper $facetHelper = null
) {
parent::__construct($options, $configLoader);
$this->facetHelper = $facetHelper;
// Use basic facet limit by default, if set:
$config = $configLoader->get($options->getFacetsIni());
$this->initFacetLimitsFromConfig($config->Results_Settings ?? null);
$this->initFacetRestrictionsFromConfig($config->Results_Settings ?? null);
if (isset($config->LegacyFields)) {
$this->facetAliases = $config->LegacyFields->toArray();
}
if (
isset($config->Results_Settings->sorted_by_index)
&& count($config->Results_Settings->sorted_by_index) > 0
) {
$this->setIndexSortedFacets(
$config->Results_Settings->sorted_by_index->toArray()
);
}
}
/**
* Return the current filters as an array of strings ['field:filter']
*
* @return array $filterQuery
*/
public function getFilterSettings()
{
// Define Filter Query
$filterQuery = [];
$orFilters = [];
$filterList = array_merge_recursive(
$this->getHiddenFilters(),
$this->filterList
);
foreach ($filterList as $field => $filter) {
if ($orFacet = str_starts_with($field, '~')) {
$field = substr($field, 1);
}
foreach ($filter as $value) {
// Special case -- complex filter, that should be taken as-is:
if ($field == '#') {
$q = $value;
} elseif (
str_ends_with($value, '*')
|| preg_match('/\[[^\]]+\s+TO\s+[^\]]+\]/', $value)
) {
// Special case -- allow trailing wildcards and ranges
$q = $field . ':' . $value;
} else {
$q = $field . ':"' . addcslashes($value, '"\\') . '"';
}
if ($orFacet) {
$orFilters[$field] ??= [];
$orFilters[$field][] = $q;
} else {
$filterQuery[] = $q;
}
}
}
foreach ($orFilters as $field => $parts) {
$filterQuery[] = '{!tag=' . $field . '_filter}' . $field
. ':(' . implode(' OR ', $parts) . ')';
}
return $filterQuery;
}
/**
* Return current facet configurations
*
* @return array $facetSet
*/
public function getFacetSettings()
{
// Build a list of facets we want from the index
$facetSet = [];
if (!empty($this->facetConfig)) {
$facetSet['limit'] = $this->facetLimit;
foreach (array_keys($this->facetConfig) as $facetField) {
$fieldLimit = $this->getFacetLimitForField($facetField);
if ($fieldLimit != $this->facetLimit) {
$facetSet["f.{$facetField}.facet.limit"] = $fieldLimit;
}
$fieldPrefix = $this->getFacetPrefixForField($facetField);
if (!empty($fieldPrefix)) {
$facetSet["f.{$facetField}.facet.prefix"] = $fieldPrefix;
}
$fieldMatches = $this->getFacetMatchesForField($facetField);
if (!empty($fieldMatches)) {
$facetSet["f.{$facetField}.facet.matches"] = $fieldMatches;
}
if ($this->getFacetOperator($facetField) == 'OR') {
$facetField = '{!ex=' . $facetField . '_filter}' . $facetField;
}
$facetSet['field'][] = $facetField;
}
if ($this->facetContains != null) {
$facetSet['contains'] = $this->facetContains;
}
if ($this->facetContainsIgnoreCase != null) {
$facetSet['contains.ignoreCase']
= $this->facetContainsIgnoreCase ? 'true' : 'false';
}
if ($this->facetOffset != null) {
$facetSet['offset'] = $this->facetOffset;
}
if ($this->facetPrefix != null) {
$facetSet['prefix'] = $this->facetPrefix;
}
$facetSet['sort'] = $this->facetSort ?: 'count';
if ($this->indexSortedFacets != null) {
foreach ($this->indexSortedFacets as $field) {
$facetSet["f.{$field}.facet.sort"] = 'index';
}
}
}
return $facetSet;
}
/**
* Initialize the object's search settings from a request object.
*
* @param \Laminas\Stdlib\Parameters $request Parameter object representing user
* request.
*
* @return void
*/
protected function initSearch($request)
{
// Special case -- did we get a list of IDs instead of a standard query?
$ids = $request->get('overrideIds', null);
if (is_array($ids)) {
$this->setQueryIDs($ids);
} else {
// Use standard initialization:
parent::initSearch($request);
}
}
/**
* Set Facet Contains
*
* @param string $p the new contains value
*
* @return void
*/
public function setFacetContains($p)
{
$this->facetContains = $p;
}
/**
* Set Facet Contains Ignore Case
*
* @param bool $val the new boolean value
*
* @return void
*/
public function setFacetContainsIgnoreCase($val)
{
$this->facetContainsIgnoreCase = $val;
}
/**
* Set Facet Offset
*
* @param int $o the new offset value
*
* @return void
*/
public function setFacetOffset($o)
{
$this->facetOffset = $o;
}
/**
* Set Facet Prefix
*
* @param string $p the new prefix value
*
* @return void
*/
public function setFacetPrefix($p)
{
$this->facetPrefix = $p;
}
/**
* Set Facet Sorting
*
* @param string $s the new sorting action value
*
* @return void
*/
public function setFacetSort($s)
{
$this->facetSort = $s;
}
/**
* Set Index Facet Sorting
*
* @param array $s the facets sorted by index
*
* @return void
*/
public function setIndexSortedFacets(array $s)
{
$this->indexSortedFacets = $s;
}
/**
* Initialize facet settings for the specified configuration sections.
*
* @param string $facetList Config section containing fields to activate
* @param string $facetSettings Config section containing related settings
* @param string $cfgFile Name of configuration to load (null to load
* default facets configuration).
*
* @return bool True if facets set, false if no settings found
*/
protected function initFacetList($facetList, $facetSettings, $cfgFile = null)
{
$config = $this->configLoader
->get($cfgFile ?? $this->getOptions()->getFacetsIni());
$this->initFacetLimitsFromConfig($config->$facetSettings ?? null);
return parent::initFacetList($facetList, $facetSettings, $cfgFile);
}
/**
* Initialize facet settings for the advanced search screen.
*
* @return void
*/
public function initAdvancedFacets()
{
$this->initFacetList('Advanced', 'Advanced_Settings');
}
/**
* Initialize facet settings for the home page.
*
* @return void
*/
public function initHomePageFacets()
{
// Load Advanced settings if HomePage settings are missing (legacy support):
if (!$this->initFacetList('HomePage', 'HomePage_Settings')) {
$this->initAdvancedFacets();
}
}
/**
* Initialize facet settings for the new items page.
*
* @return void
*/
public function initNewItemsFacets()
{
// Load Advanced settings if NewItems settings are missing (fallback to defaults):
if (!$this->initFacetList('NewItems', 'NewItems_Settings')) {
$this->initAdvancedFacets();
}
}
/**
* Add filters to the object based on values found in the request object.
*
* @param \Laminas\Stdlib\Parameters $request Parameter object representing user
* request.
*
* @return void
*/
protected function initFilters($request)
{
// Use the default behavior of the parent class, but add support for the
// special illustrations filter.
parent::initFilters($request);
switch ($request->get('illustration', -1)) {
case 1:
$this->addFilter('illustrated:Illustrated');
break;
case 0:
$this->addFilter('illustrated:"Not Illustrated"');
break;
}
}
/**
* Override the normal search behavior with an explicit array of IDs that must
* be retrieved.
*
* @param array $ids Record IDs to load
*
* @return void
*/
public function setQueryIDs($ids)
{
// No need for spell checking or highlighting on an ID query!
$this->getOptions()->spellcheckEnabled(false);
$this->getOptions()->disableHighlighting();
// Special case -- no IDs to set:
if (empty($ids)) {
$this->setOverrideQuery('NOT *:*');
return;
}
$callback = function ($i) {
return '"' . addcslashes($i, '"') . '"';
};
$ids = array_map($callback, $ids);
$this->searchingById = true;
$this->setOverrideQuery('id:(' . implode(' OR ', $ids) . ')');
}
/**
* Get the maximum number of IDs that may be sent to setQueryIDs (-1 for no
* limit).
*
* @return int
*/
public function getQueryIDLimit()
{
$config = $this->configLoader->get($this->getOptions()->getMainIni());
return $config->Index->maxBooleanClauses ?? 1024;
}
/**
* Normalize sort parameters.
*
* @param string $sort Sort parameter
*
* @return string
*/
protected function normalizeSort($sort)
{
static $table = [
'year' => ['field' => 'publishDateSort', 'order' => 'desc'],
'publishDateSort' => ['field' => 'publishDateSort', 'order' => 'desc'],
'author' => ['field' => 'author_sort', 'order' => 'asc'],
'authorStr' => ['field' => 'author_sort', 'order' => 'asc'],
'title' => ['field' => 'title_sort', 'order' => 'asc'],
'relevance' => ['field' => 'score', 'order' => 'desc'],
'callnumber' => ['field' => 'callnumber-sort', 'order' => 'asc'],
];
$tieBreaker = $this->getOptions()->getSortTieBreaker();
if ($tieBreaker) {
$sort .= ',' . $tieBreaker;
}
$normalized = [];
$fields = [];
foreach (explode(',', $sort) as $component) {
$parts = explode(' ', trim($component));
$field = reset($parts);
$order = next($parts);
if (isset($table[$field])) {
$normalized[] = sprintf(
'%s %s',
$table[$field]['field'],
$order ?: $table[$field]['order']
);
$fields[] = $field;
} else {
if (!in_array($field, $fields)) {
$normalized[] = sprintf(
'%s %s',
$field,
$order ?: 'asc'
);
$fields[] = $field;
}
}
}
return implode(',', $normalized);
}
/**
* Create search backend parameters for advanced features.
*
* @return ParamBag
*/
public function getBackendParameters()
{
$backendParams = new ParamBag();
// Spellcheck
$backendParams->set(
'spellcheck',
$this->getOptions()->spellcheckEnabled() ? 'true' : 'false'
);
// Facets
$facets = $this->getFacetSettings();
if (!empty($facets)) {
$backendParams->add('facet', 'true');
foreach ($facets as $key => $value) {
// prefix keys with "facet" unless they already have a "f." prefix:
$fullKey = str_starts_with($key, 'f.') ? $key : "facet.$key";
$backendParams->add($fullKey, $value);
}
$backendParams->add('facet.mincount', 1);
}
// Filters
$filters = $this->getFilterSettings();
foreach ($filters as $filter) {
$backendParams->add('fq', $filter);
}
// Shards
$allShards = $this->getOptions()->getShards();
$shards = $this->getSelectedShards();
if (empty($shards)) {
$shards = array_keys($allShards);
}
// If we have selected shards, we need to format them:
if (!empty($shards)) {
$selectedShards = [];
foreach ($shards as $current) {
$selectedShards[$current] = $allShards[$current];
}
$backendParams->add('shards', implode(',', $selectedShards));
}
// Sort
$sort = $this->getSort();
if ($sort) {
// If we have an empty search with relevance sort as the primary sort
// field, see if there is an override configured:
$sortFields = explode(',', $sort);
$allTerms = trim($this->getQuery()->getAllTerms() ?? '');
if (
'relevance' === $sortFields[0]
&& ('' === $allTerms || '*:*' === $allTerms || $this->searchingById)
&& ($relOv = $this->getOptions()->getEmptySearchRelevanceOverride())
) {
$sort = $relOv;
}
$backendParams->add('sort', $this->normalizeSort($sort));
}
// Highlighting -- on by default, but we should disable if necessary:
if (!$this->getOptions()->highlightEnabled()) {
$backendParams->add('hl', 'false');
}
// Pivot facets for visual results
if ($pf = $this->getPivotFacets()) {
$backendParams->add('facet.pivot', $pf);
$backendParams->set('facet', 'true');
}
return $backendParams;
}
/**
* Set pivot facet fields to use for visual results
*
* @param string $facets A comma-separated list of fields
*
* @return void
*/
public function setPivotFacets($facets)
{
$this->pivotFacets = $facets;
}
/**
* Get pivot facet information for visual facets
*
* @return string
*/
public function getPivotFacets()
{
return $this->pivotFacets;
}
/**
* Format a single filter for use in getFilterList().
*
* @param string $field Field name
* @param string $value Field value
* @param string $operator Operator (AND/OR/NOT)
* @param bool $translate Should we translate the label?
*
* @return array
*/
protected function formatFilterListEntry($field, $value, $operator, $translate)
{
$filter = parent::formatFilterListEntry(
$field,
$value,
$operator,
$translate
);
$hierarchicalFacets = $this->getOptions()->getHierarchicalFacets();
$hierarchicalFacetSeparators
= $this->getOptions()->getHierarchicalFacetSeparators();
// Convert range queries to a language-non-specific format:
$caseInsensitiveRegex = '/^\(\[(.*) TO (.*)\] OR \[(.*) TO (.*)\]\)$/';
if (preg_match('/^\[(.*) TO (.*)\]$/', $value, $matches)) {
// Simple case: [X TO Y]
$filter['displayText'] = $matches[1] . ' - ' . $matches[2];
} elseif (preg_match($caseInsensitiveRegex, $value, $matches)) {
// Case insensitive case: [x TO y] OR [X TO Y]; convert
// only if values in both ranges match up!
if (
strtolower($matches[3]) == strtolower($matches[1])
&& strtolower($matches[4]) == strtolower($matches[2])
) {
$filter['displayText'] = $matches[1] . ' - ' . $matches[2];
}
} elseif ($this->facetHelper && in_array($field, $hierarchicalFacets)) {
// Display hierarchical facet levels nicely
$separator = $hierarchicalFacetSeparators[$field] ?? '/';
if (!$translate) {
$filter['displayText'] = $this->facetHelper->formatDisplayText(
$filter['displayText'],
true,
$separator
)->getDisplayString();
} else {
$domain = $this->getOptions()
->getTextDomainForTranslatedFacet($field);
// Provide translation of each separate element as a default
// while allowing one to translate the full string too:
$parts = $this->facetHelper
->getFilterStringParts($filter['value']);
$translated = [];
foreach ($parts as $part) {
$translated[] = $this->translate([$domain, $part]);
}
$translatedParts = implode($separator, $translated);
$parts = array_map(
function ($part) {
return $part->getDisplayString();
},
$parts
);
$str = implode($separator, $parts);
$filter['displayText']
= $this->translate([$domain, $str], [], $translatedParts);
}
}
return $filter;
}
/**
* Get information on the current state of the boolean checkbox facets.
*
* @param array $include List of checkbox filters to return (null for all)
* @param bool $includeDynamic Should we include dynamically-generated
* checkboxes that are not part of the include list above?
*
* @return array
*/
public function getCheckboxFacets(
array $include = null,
bool $includeDynamic = true
) {
// Grab checkbox facet details using the standard method:
$facets = parent::getCheckboxFacets($include, $includeDynamic);
$config = $this->configLoader->get($this->getOptions()->getFacetsIni());
$filterField = $config->CustomFilters->custom_filter_field ?? 'vufind';
// Special case -- inverted checkbox facets should always appear, even on
// the "no results" screen, since setting them actually EXPANDS rather than
// reduces the result set.
foreach ($facets as $i => $facet) {
// Append colon on end to ensure that $customFilter is always set.
[$field, $customFilter] = explode(':', $facet['filter'] . ':');
if (
$field == $filterField
&& isset($config->CustomFilters->inverted_filters[$customFilter])
) {
$facets[$i]['alwaysVisible'] = true;
}
}
// Return modified list:
return $facets;
}
}