forked from EeroHeikkinen/MuseumTheme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solr.php
executable file
·2349 lines (2118 loc) · 83.1 KB
/
Solr.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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Solr HTTP Interface
*
* PHP version 5
*
* Copyright (C) Villanova University 2007.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* @category VuFind
* @package Support_Classes
* @author Andrew S. Nagy <vufind-tech@lists.sourceforge.net>
* @author Demian Katz <demian.katz@villanova.edu>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/system_classes#index_interface Wiki
*/
require_once 'sys/Proxy_Request.php';
require_once 'sys/IndexEngine.php';
require_once 'sys/ConfigArray.php';
require_once 'sys/SolrUtils.php';
require_once 'services/MyResearch/lib/Change_tracker.php';
require_once 'XML/Unserializer.php';
require_once 'XML/Serializer.php';
/**
* Solr HTTP Interface
*
* @category VuFind
* @package Support_Classes
* @author Andrew S. Nagy <vufind-tech@lists.sourceforge.net>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://vufind.org/wiki/system_classes#index_interface Wiki
*/
class Solr implements IndexEngine
{
/**
* A boolean value determining whether to print debug information
* @var bool
*/
public $debug = false;
/**
* Whether to Serialize to a PHP Array or not.
* @var bool
*/
public $raw = false;
/**
* The HTTP_Request object used for REST transactions
* @var object HTTP_Request
*/
public $client;
/**
* The host to connect to
* @var string
*/
public $host;
/**
* The core being used on the host
* @var string
*/
public $core;
/**
* The status of the connection to Solr
* @var string
*/
public $status = false;
/**
* An array of characters that are illegal in search strings
*/
private $_illegal = array('!', ':', ';', '[', ']', '{', '}');
/**
* The path to the YAML file specifying available search types:
*/
protected $searchSpecsFile = 'conf/searchspecs.yaml';
/**
* An array of search specs pulled from $searchSpecsFile (above)
*/
private $_searchSpecs = false;
/**
* Should boolean operators in the search string be treated as
* case-insensitive (false), or must they be ALL UPPERCASE (true)?
*/
private $_caseSensitiveBooleans = true;
/**
* Should range operators (i.e. [a TO b]) in the search string be treated as
* case-insensitive (false), or must they be ALL UPPERCASE (true)? Note that
* making this setting case insensitive not only changes the word "TO" to
* uppercase but also inserts OR clauses to check for case insensitive matches
* against the edges of the range... i.e. ([a TO b] OR [A TO B]).
*/
private $_caseSensitiveRanges = true;
/**
* Selected shard settings.
*/
private $_solrShards = array();
private $_solrShardsFieldsToStrip = array();
/**
* Should we collect highlighting data?
*/
private $_highlight = false;
/**
* How should we cache the search specs?
*/
private $_specCache = false;
/**
* Whether merged records are in use
*/
private $_mergedRecords = null;
/**
* Comma-separated list of data source codes to search in order of priority (most desired first)
*/
private $_recordSources = '';
/**
* Array of buildings in facet query, used to override configured merge priority
*/
private $_mergeBuildingPriority = array();
/**
* Preferred record source
*/
private $_preferredRecordSource = null;
/**
* Whether to filter out component parts merged with host records
*/
private $_hideComponentParts = false;
/**
* Unicode normalization to perform. Valid values are empty, NFC, NFD, NFKC and NFKD.
*/
private $_unicodeNormalizationForm = '';
/**
* Constructor
*
* @param string|string[] $hosts The URL(s) for the local Solr Server
* @param string $index The core to use on the specified server
*
* @access public
*/
public function __construct($hosts, $index = '')
{
global $configArray;
// Set a default Solr index if none is provided to the constructor:
if (empty($index)) {
$this->core = isset($configArray['Index']['default_core']) ?
$configArray['Index']['default_core'] : "biblio";
} else {
$this->core = $index;
}
if (!is_array($hosts)) {
$hosts = array($hosts);
}
for ($i = 0; $i < count($hosts); $i++) {
$host = $hosts[$i];
$this->host = $host . '/' . $this->core;
// Test to see solr is online
$test_url = $this->host . "/admin/ping";
$test_client = new Proxy_Request();
$test_client->setMethod(HTTP_REQUEST_METHOD_GET);
$test_client->setURL($test_url);
PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
$result = $test_client->sendRequest();
PEAR::popErrorHandling();
if (!PEAR::isError($result)) {
// Even if we get a response, make sure it's a 'good' one.
if ($test_client->getResponseCode() != 200) {
if ($i == count($hosts) - 1) {
// Last possible host, raise an error
PEAR::raiseError('Solr index is offline.');
}
continue;
}
} else {
if ($i == count($hosts) - 1) {
// Last possible host, raise an error
PEAR::raiseError($result);
}
continue;
}
// Test was successful, use this host
break;
}
// If we're still processing then solr is online
$this->client = new Proxy_Request(null, array('useBrackets' => false));
// Read in preferred boolean/range behavior:
$searchSettings = getExtraConfigArray('searches');
if (isset($searchSettings['General']['case_sensitive_bools'])) {
$this->_caseSensitiveBooleans
= $searchSettings['General']['case_sensitive_bools'];
}
if (isset($searchSettings['General']['case_sensitive_ranges'])) {
$this->_caseSensitiveRanges
= $searchSettings['General']['case_sensitive_ranges'];
}
// Turn on highlighting if the user has requested highlighting or snippet
// functionality:
$highlight = !isset($searchSettings['General']['highlighting'])
? false : $searchSettings['General']['highlighting'];
$snippet = !isset($searchSettings['General']['snippets'])
? false : $searchSettings['General']['snippets'];
if ($highlight || $snippet) {
$this->_highlight = true;
}
// Deal with field-stripping shard settings:
if (isset($searchSettings['StripFields'])
&& is_array($searchSettings['StripFields'])
) {
$this->_solrShardsFieldsToStrip = $searchSettings['StripFields'];
}
// Deal with search spec cache setting:
if (isset($searchSettings['Cache']['type'])) {
$this->_specCache = $searchSettings['Cache']['type'];
}
// Deal with session-based shard settings (but only in the main Solr class;
// shard settings will mess up subclasses):
if (isset($_SESSION['shards']) && get_class($this) == 'Solr') {
$shards = array();
foreach ($_SESSION['shards'] as $current) {
if (isset($configArray['IndexShards'][$current])) {
$shards[$current] = $configArray['IndexShards'][$current];
}
}
// if only one shard is used, take its URL as SOLR-Host-URL
if (count($shards) === 1) {
$shardsKeys = array_keys($shards);
$this->host = 'http://'.$shards[$shardsKeys[0]];
}
// always set the shards -- even if only one is selected, we may
// need to filter fields and facets:
$this->setShards($shards);
}
// Merged records
if (isset($searchSettings['Records']['merged_records'])) {
$this->_mergedRecords = $searchSettings['Records']['merged_records'];
$this->_recordSources = isset($searchSettings['Records']['sources']) ? $searchSettings['Records']['sources'] : '';
$this->setPreferredRecordSource();
}
// Hide component parts?
if (isset($searchSettings['General']['hide_component_parts'])) {
$this->_hideComponentParts
= $searchSettings['General']['hide_component_parts'];
}
// Use UNICODE normalization?
if (isset($configArray['Index']['unicode_normalization_form'])) {
$this->_unicodeNormalizationForm
= $configArray['Index']['unicode_normalization_form'];
}
}
/**
* Is this object configured with case-sensitive boolean operators?
*
* @return boolean
* @access public
*/
public function hasCaseSensitiveBooleans()
{
return $this->_caseSensitiveBooleans;
}
/**
* Is this object configured with case-sensitive range operators?
*
* @return boolean
* @access public
*/
public function hasCaseSensitiveRanges()
{
return $this->_caseSensitiveRanges;
}
/**
* Support method for _getSearchSpecs() -- load the specs from cache or disk.
*
* @return void
* @access private
*/
private function _loadSearchSpecs()
{
global $configArray;
// Turn relative path into absolute path:
$fullPath = $configArray['Site']['local'] . '/' . $this->searchSpecsFile;
// Check for a local override file:
$local = str_replace('.yaml', '.local.yaml', $fullPath);
$local = file_exists($local) ? $local : false;
// Generate cache key:
$key = basename($fullPath) . '-' . filemtime($fullPath);
if ($local) {
$key .= '-' . basename($local) . '-' . filemtime($local);
}
$key = md5($key);
// Load cache manager:
$cache = new VuFindCache($this->_specCache, 'searchspecs');
// Generate data if not found in cache:
if (!($results = $cache->load($key))) {
$results = Horde_Yaml::load(file_get_contents($fullPath));
if ($local) {
$localResults = Horde_Yaml::load(file_get_contents($local));
foreach ($localResults as $key => $value) {
$results[$key] = $value;
}
}
$cache->save($results, $key);
}
$this->_searchSpecs = $results;
}
/**
* Get the search specifications loaded from the specified YAML file.
*
* @param string $handler The named search to provide information about (set
* to null to get all search specifications)
* @param string $query The query string
*
* @return mixed Search specifications array if available, false if an invalid
* search is specified.
* @access private
*/
private function _getSearchSpecs($handler = null, $query = null)
{
// Only load specs once:
if ($this->_searchSpecs === false) {
$this->_loadSearchSpecs();
}
// Special case -- null $handler means we want all search specs.
if (is_null($handler)) {
return $this->_searchSpecs;
}
// Check for phrase search and exact search spec version
if (isset($query) && substr(trim($query), 0, 1) == '"' && substr(trim($query), -1, 1) == '"') {
if (isset($this->_searchSpecs["{$handler}Exact"])) {
return $this->_searchSpecs["{$handler}Exact"];
}
}
// Return specs on the named search if found (easiest, most common case).
if (isset($this->_searchSpecs[$handler])) {
return $this->_searchSpecs[$handler];
}
// Check for a case-insensitive match -- this provides backward
// compatibility with different cases used in early VuFind versions
// and allows greater tolerance of minor typos in config files.
foreach ($this->_searchSpecs as $name => $specs) {
if (strcasecmp($name, $handler) == 0) {
return $specs;
}
}
// If we made it this far, no search specs exist -- return false.
return false;
}
/**
* Retrieves a document specified by the ID.
*
* @param string $id The document to retrieve from Solr
*
* @throws object PEAR Error
* @return string The requested resource (or null if bad ID)
* @access public
*/
public function getRecord($id)
{
if ($this->debug) {
echo "<pre>Get Record: $id</pre>\n";
}
// Query String Parameters
$options = array('q' => 'id:"' . addcslashes($id, '"') . '"');
if (get_class($this) == 'Solr') {
include_once 'sys/SearchObject/Solr.php';
$filters = SearchObject_Solr::getDefaultHiddenFilters();
if (!empty($filters)) {
$options['fq'] = $filters;
}
}
// TODO: make this nicer, such as an argument to _select
$saveMerged = $this->_mergedRecords;
$this->_mergedRecords = false;
$result = $this->_select('GET', $options);
$this->_mergedRecords = $saveMerged;
if (PEAR::isError($result)) {
PEAR::raiseError($result);
}
return isset($result['response']['docs'][0]) ?
$result['response']['docs'][0] : null;
}
/**
* Retrieves documents specified by the ID array.
*
* @param array $ids The document IDs to retrieve from Solr
* @param bool $merged Whether to handle merged records (defaults to true)
*
* @throws object PEAR Error
* @return string The requested resources (or null if bad ID)
* @access public
*/
public function getRecords($ids, $merged = true)
{
if ($this->debug) {
echo "<pre>Get Records: " . print_r($ids) . "</pre>\n";
}
// Query String Parameters
foreach ($ids as &$id) {
$id = '"' . addcslashes($id, '"') . '"';
}
$options = array(
'q' => 'id:(' . implode(' OR ', $ids) . ')',
'rows' => count($ids)
);
// TODO: make this nicer, such as an argument to _select
$saveMerged = $this->_mergedRecords;
$this->_mergedRecords = $merged;
$result = $this->_select('GET', $options);
$this->_mergedRecords = $saveMerged;
if (PEAR::isError($result)) {
PEAR::raiseError($result);
}
return isset($result['response']['docs'])
? $result['response']['docs'] : null;
}
/**
* Get records similiar to one record
* Uses MoreLikeThis Request Handler
*
* Uses SOLR MLT Query Handler
*
* @param string $id A Solr document ID.
* @param array $extras Extra parameters to pass to Solr (optional)
*
* @throws object PEAR Error
* @return array An array of query results similar to the specified record
* @access public
*/
public function getMoreLikeThis($id, $extras = array())
{
// Query String Parameters
$options = $extras + array(
'q' => 'id:"' . addcslashes($id, '"') . '"',
'qt' => 'morelikethis'
);
if ($this->_mergedRecords) {
// Filter out merged children by default
if (!isset($filter)) {
$filter = array();
}
$filter[] = '-merged_child_boolean:TRUE';
$filter[] = '-local_ids_str_mv:"' . addcslashes($id, '"') . '"';
} elseif ($this->_mergedRecords !== null) {
// Filter out merged records by default
if (!isset($filter)) {
$filter = array();
}
$filter[] = '-merged_boolean:TRUE';
}
if ($this->_hideComponentParts) {
// Filter out component parts by default
if (!isset($filter)) {
$filter = array();
}
$filter[] = '-hidden_component_boolean:TRUE';
}
// Data source filters
if ($this->_recordSources) {
$sources = array_map(
function($input) {
return '"' . addcslashes($input, '"') . '"';
},
explode(',', $this->_recordSources)
);
$filter[] = 'source_str_mv:(' . implode(' OR ', $sources) . ')';
}
if (isset($filter)) {
$options['fq'] = $filter;
}
// Build Filter Query
if (is_array($filter) && count($filter)) {
$options['fq'] = $filter;
}
$result = $this->_select('GET', $options);
if (PEAR::isError($result)) {
PEAR::raiseError($result);
}
return $result;
}
/**
* Get record data based on the provided field and phrase.
* Used for AJAX suggestions.
*
* @param string $phrase The input phrase
* @param string $field The field to search on
* @param int $limit The number of results to return
*
* @return array An array of query results
* @access public
*/
public function getSuggestion($phrase, $field, $limit)
{
if (!strlen($phrase)) {
return null;
}
// Ignore illegal characters
$phrase = str_replace($this->_illegal, '', $phrase);
// Process Search
$query = "$field:($phrase*)";
$result = $this->search(
$query, null, null, 0, $limit,
array('field' => $field, 'limit' => $limit)
);
return $result['facet_counts']['facet_fields'][$field];
}
/**
* Internal method to build query string from search parameters
*
* @param array $structure The SearchSpecs-derived structure or substructure
* defining the search, derived from the yaml file
* @param array $values The various values in an array with keys
* 'onephrase', 'and', 'or' (and perhaps others)
* @param string $joiner The operator used to combine generated clauses
*
* @throws object PEAR Error
* @return string A search string suitable for adding to a query URL
* @access private
*/
private function _applySearchSpecs($structure, $values, $joiner = "OR")
{
$clauses = array();
foreach ($structure as $field => $clausearray) {
if (is_numeric($field)) {
// shift off the join string and weight
$sw = array_shift($clausearray);
$internalJoin = ' ' . $sw[0] . ' ';
// Build it up recursively
$sstring = '(' .
$this->_applySearchSpecs($clausearray, $values, $internalJoin) .
')';
// ...and add a weight if we have one
$weight = $sw[1];
if (!is_null($weight) && $weight && $weight > 0) {
$sstring .= '^' . $weight;
}
// push it onto the stack of clauses
$clauses[] = $sstring;
} else if (!$this->_isStripped($field)) {
// Otherwise, we've got a (list of) [munge, weight] pairs to deal
// with
foreach ($clausearray as $spec) {
// build a string like title:("one two")
$sstring = $field . ':(' . $values[$spec[0]] . ')';
// Add the weight if we have one. Yes, I know, it's redundant
// code.
$weight = $spec[1];
if (!is_null($weight) && $weight && $weight > 0) {
$sstring .= '^' . $weight;
}
// ..and push it on the stack of clauses
$clauses[] = $sstring;
}
}
}
// Join it all together
return implode(' ' . $joiner . ' ', $clauses);
}
/**
* _getStrippedFields -- internal method to read the fields that should get
* stripped for the used shards from config file
*
* @return array An array containing any field that should be stripped from query
* @access private
*/
private function _getStrippedFields()
{
// Store stripped fields as a static variable so that we only need to
// process the configuration settings once:
static $strippedFields = false;
if ($strippedFields === false) {
$strippedFields = array();
foreach ($this->_solrShards as $index => $address) {
if (array_key_exists($index, $this->_solrShardsFieldsToStrip)) {
$parts = explode(',', $this->_solrShardsFieldsToStrip[$index]);
foreach ($parts as $part) {
$strippedFields[] = trim($part);
}
}
}
$strippedFields = array_unique($strippedFields);
}
return $strippedFields;
}
/**
* _isStripped -- internal method to check if a field is stripped from query
*
* @param string $field The name of the field that should be checked for
* stripping
*
* @return bool A boolean value indicating whether the field should be
* stripped (true) or not (false)
* @access private
*/
private function _isStripped($field)
{
// Never strip fields if shards are disabled.
// Return true if the current field needs to be stripped.
if (!empty($this->_solrShards)
&& in_array($field, $this->_getStrippedFields())
) {
return true;
}
return false;
}
/**
* Given a field name and search string, return an array containing munged
* versions of the search string for use in _applySearchSpecs().
*
* @param string $field The YAML search spec field name to search
* @param string $lookfor The string to search for in the field
* @param array $custom Custom munge settings from YAML search specs
* @param bool $basic Is $lookfor a basic (true) or advanced (false) query?
*
* @return array Array for use as _applySearchSpecs() values param
* @access private
*/
private function _buildMungeValues($field, $lookfor, $custom = null,
$basic = true
) {
// Only tokenize basic queries:
if ($basic) {
// Tokenize Input
$tokenized = $this->tokenizeInput($lookfor);
// Create AND'd and OR'd queries
$andQuery = implode(' AND ', $tokenized);
$orQuery = implode(' OR ', $tokenized);
// Build possible inputs for searching:
$values = array();
$values['onephrase']
= '"' . str_replace('"', '', implode(' ', $tokenized)) . '"';
$values['and'] = $andQuery;
$values['or'] = $orQuery;
} else {
// If we're skipping tokenization, we just want to pass $lookfor through
// unmodified (it's probably an advanced search that won't benefit from
// tokenization). We'll just set all possible values to the same thing,
// except that we'll try to do the "one phrase" in quotes if possible.
// IMPORTANT: If we detect a boolean NOT, we MUST omit the quotes.
$onephrase = (strstr($lookfor, '"') || strstr($lookfor, ' NOT '))
? $lookfor : '"' . $lookfor . '"';
$values = array(
'onephrase' => $onephrase, 'and' => $lookfor, 'or' => $lookfor
);
}
// Apply custom munge operations if necessary:
if (is_array($custom)) {
foreach ($custom as $mungeName => $mungeOps) {
$values[$mungeName] = $lookfor;
// Skip munging of advanced queries:
if ($basic) {
foreach ($mungeOps as $operation) {
switch($operation[0]) {
case 'append':
$values[$mungeName] .= $operation[1];
break;
case 'lowercase':
$values[$mungeName] = strtolower($values[$mungeName]);
break;
case 'preg_replace':
$values[$mungeName] = preg_replace(
$operation[1], $operation[2], $values[$mungeName]
);
break;
case 'uppercase':
$values[$mungeName] = strtoupper($values[$mungeName]);
break;
}
}
}
}
}
return $values;
}
/**
* Given a field name and search string, expand this into the necessary Lucene
* query to perform the specified search on the specified field(s).
*
* @param string $field The YAML search spec field name to search
* @param string $lookfor The string to search for in the field
* @param bool $basic Is $lookfor a basic (true) or advanced (false) query?
*
* @return string The query
* @access private
*/
private function _buildQueryComponent($field, $lookfor, $basic = true)
{
// Load the YAML search specifications:
$ss = $this->_getSearchSpecs($field, $lookfor);
// If we received a field spec that wasn't defined in the YAML file,
// let's try simply passing it along to Solr.
if ($ss === false) {
return $field . ':(' . $lookfor . ')';
}
// If this is a basic query and we have Dismax settings, let's build
// a Dismax subquery to avoid some of the ugly side effects of our Lucene
// query generation logic.
if ($basic && isset($ss['DismaxFields'])) {
$qf = implode(' ', $ss['DismaxFields']);
$dmParams = '';
if (isset($ss['DismaxParams']) && is_array($ss['DismaxParams'])) {
foreach ($ss['DismaxParams'] as $current) {
$dmParams .= ' ' . $current[0] . "='" .
addcslashes($current[1], "'") . "'";
}
}
$dismaxQuery = '{!dismax qf="' . $qf . '"' . $dmParams . '}' . $lookfor;
$baseQuery = '_query_:"' . addslashes($dismaxQuery) . '"';
} else {
// Munge the user query in a few different ways:
$customMunge = isset($ss['CustomMunge']) ? $ss['CustomMunge'] : null;
$values
= $this->_buildMungeValues($field, $lookfor, $customMunge, $basic);
// Apply the $searchSpecs property to the data:
$baseQuery = $this->_applySearchSpecs($ss['QueryFields'], $values);
}
// Apply filter query if applicable:
if (isset($ss['FilterQuery'])) {
return "({$baseQuery}) AND ({$ss['FilterQuery']})";
}
return "($baseQuery)";
}
/**
* Given a field name and search string known to contain advanced features
* (as identified by isAdvanced()), expand this into the necessary Lucene
* query to perform the specified search on the specified field(s).
*
* @param string $handler The YAML search spec field name to search
* @param string $query The string to search for in the field
*
* @return string The query
* @access private
*/
private function _buildAdvancedQuery($handler, $query)
{
$query = $this->_buildAdvancedInnerQuery($handler, $query);
// Apply boost query/boost function, if any:
$ss = $this->_getSearchSpecs($handler, $query);
$bq = array();
if (isset($ss['DismaxParams']) && is_array($ss['DismaxParams'])) {
foreach ($ss['DismaxParams'] as $current) {
if ($current[0] == 'bq') {
$bq[] = $current[1];
} else if ($current[0] == 'bf') {
// BF parameter may contain multiple space-separated functions
// with individual boosts. We need to parse this into _val_
// query components:
$bfParts = explode(' ', $current[1]);
foreach ($bfParts as $bf) {
$bf = trim($bf);
if (!empty($bf)) {
$bfSubParts = explode('^', $bf, 2);
$boost = '"' . addcslashes($bfSubParts[0], '"') . '"';
if (isset($bfSubParts[1])) {
$boost .= '^' . $bfSubParts[1];
}
$bq[] = '_val_:' . $boost;
}
}
}
}
}
if (!empty($bq)) {
$query = '(' . $query . ') AND (*:* OR ' . implode(' OR ', $bq) . ')';
}
return $query;
}
/**
* Support method for _buildAdvancedQuery -- build the inner portion of the
* query; the calling method may then wrap this with additional settings.
*
* @param string $handler The YAML search spec field name to search
* @param string $query The string to search for in the field
*
* @return string The query
* @access private
*/
private function _buildAdvancedInnerQuery($handler, $query)
{
// Special case -- if the user wants all records but the current handler
// has a filter query, apply the filter query:
if (trim($query) == '*:*') {
$ss = $this->_getSearchSpecs($handler);
if (isset($ss['FilterQuery'])) {
return $ss['FilterQuery'];
}
}
// Strip out any colons that are NOT part of a field specification:
$query = preg_replace('/(\:\s+|\s+:)/', ' ', $query);
// If the query already includes field specifications, we can't easily
// apply it to other fields through our defined handlers, so we'll leave
// it as-is:
if (strstr($query, ':')) {
return $query;
}
// Convert empty queries to return all values in a field:
if (empty($query)) {
$query = '[* TO *]';
}
// If the query ends in a question mark, the user may not really intend to
// use the question mark as a wildcard -- let's account for that possibility
if (substr($query, -1) == '?') {
$query = "({$query}) OR (" . substr($query, 0, strlen($query) - 1) . ")";
}
// We're now ready to use the regular YAML query handler but with the
// $basic parameter set to false so that we leave the advanced query
// features unmolested.
return $this->_buildQueryComponent($handler, $query, false);
}
/**
* Build Query string from search parameters
*
* @param array $search An array of search parameters
*
* @throws object PEAR Error
* @return string The query
* @access public
*/
public function buildQuery($search)
{
$groups = array();
$excludes = array();
if (is_array($search)) {
$query = '';
foreach ($search as $params) {
// Advanced Search
if (isset($params['group'])) {
$thisGroup = array();
// Process each search group
foreach ($params['group'] as $group) {
// Build this group individually as a basic search
$thisGroup[] = $this->buildQuery(array($group));
}
// Is this an exclusion (NOT) group or a normal group?
if ($params['group'][0]['bool'] == 'NOT') {
$excludes[] = join(" OR ", $thisGroup);
} else {
$groups[] = join(
" " . $params['group'][0]['bool'] . " ", $thisGroup
);
}
}
// Basic Search
if (isset($params['lookfor']) && $params['lookfor'] != '') {
// Clean and validate input
$lookfor = $this->validateInput($params['lookfor']);
// Force boolean operators to uppercase if we are in a
// case-insensitive mode:
if (!$this->_caseSensitiveBooleans) {
$lookfor = VuFindSolrUtils::capitalizeBooleans($lookfor);
}
// Adjust range operators if we are in a case-insensitive mode:
if (!$this->_caseSensitiveRanges) {
$lookfor = VuFindSolrUtils::capitalizeRanges($lookfor);
}
if (isset($params['field']) && ($params['field'] != '')) {
if ($this->isAdvanced($lookfor)) {
$query .= $this->_buildAdvancedQuery(
$params['field'], $lookfor
);
} else {
$query .= $this->_buildQueryComponent(
$params['field'], $lookfor
);
}
} else {
$query .= $lookfor;
}
}
}
}
// Put our advanced search together
if (count($groups) > 0) {
$query = "(" . join(") " . $search[0]['join'] . " (", $groups) . ")";
}
// and concatenate exclusion after that
if (count($excludes) > 0) {
$query .= " NOT ((" . join(") OR (", $excludes) . "))";
}
// Ensure we have a valid query to this point
if (!isset($query) || $query == '') {
$query = '*:*';
}
return $query;
}
/**
* Normalize a sort option.
*
* @param string $sort The sort option.
*
* @return string The normalized sort value.