forked from mdnoble73/VuFind-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solr.php
2203 lines (1964 loc) · 65.5 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
/**
*
* 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
*
*/
require_once ROOT_DIR . '/sys/IndexEngine.php';
require_once ROOT_DIR . '/sys/Proxy_Request.php';
require_once ROOT_DIR . '/sys/ConfigArray.php';
require_once ROOT_DIR . '/sys/SolrUtils.php';
require_once ROOT_DIR . '/sys/VuFindCache.php';
require_once 'XML/Unserializer.php';
require_once 'XML/Serializer.php';
/**
* Solr HTTP Interface
*
* @version $Revision: 1.13 $
* @author Andrew S. Nagy <andrew.nagy@villanova.edu>
* @access public
*/
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 HTTP_Request $client
*/
public $client;
/**
* The host to connect to
* @var string
*/
public $host;
/**
* 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)
*
* @var array
*/
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;
/**
* Flag to disable default scoping to show ILL book titles, etc.
*/
private $scopingDisabled = false;
/** @var LibrarySearchSource|LocationSearchSource */
private $searchSource = null;
/**
* Constructor
*
* Sets up the SOAP Client
*
* @param string $host The URL for the local Solr Server
* @param string $index The name of the index
* @access public
*/
function __construct($host, $index = '')
{
global $configArray;
global $timer;
// Set a default Solr index if none is provided to the constructor:
if (empty($index)) {
$index = isset($configArray['Index']['default_core']) ?
$configArray['Index']['default_core'] : "biblio";
}
//Check for a more specific searchspecs file
global $serverName;
if (file_exists("../../sites/$serverName/conf/searchspecs.yaml")){
// Return the file path (note that all ini files are in the conf/ directory)
$this->searchSpecsFile = "../../sites/$serverName/conf/searchspecs.yaml";
}elseif(file_exists("../../sites/default/conf/searchspecs.yaml")){
// Return the file path (note that all ini files are in the conf/ directory)
$this->searchSpecsFile = "../../sites/default/conf/searchspecs.yaml";
}
$this->host = $host . '/' . $index;
/** @var Memcache $memCache */
global $memCache;
if ($memCache){
$pingDone = $memCache->get('solr_ping');
}else{
$pingDone = false;
}
if ($pingDone == false){
// 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);
$result = $test_client->sendRequest();
if (!PEAR_Singleton::isError($result)) {
// Even if we get a response, make sure it's a 'good' one.
if ($test_client->getResponseCode() != 200) {
PEAR_Singleton::raiseError('Solr index is offline.');
}
} else {
PEAR_Singleton::raiseError($result);
}
if ($memCache){
$memCache->set('solr_ping', true, 0, $configArray['Caching']['solr_ping']);
}
$timer->logTime('Ping Solr instance');
}
// If we're still processing then solr is online
$this->client = new Proxy_Request(null, array('useBrackets' => false));
// Read in preferred boolean 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'];
}
if (isset($_SESSION['shards'])){
$this->_loadShards($_SESSION['shards']);
}
$timer->logTime('Finish Solr Initialization');
}
private function _loadShards($newShards){
// Deal with session-based shard settings:
$shards = array();
global $configArray;
foreach ($newShards as $current) {
if (isset($configArray['IndexShards'][$current])) {
$shards[$current] = $configArray['IndexShards'][$current];
}
}
$this->setShards($shards);
}
/**
* Is this object configured with case-sensitive boolean operators?
*
* @access public
* @return boolean
*/
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()
{
// Generate cache key:
$key = md5(
basename($this->searchSpecsFile) . '-' . filemtime($this->searchSpecsFile)
);
// 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($this->searchSpecsFile)
);
$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)
*
* @return mixed Search specifications array if available, false if an invalid
* search is specified.
* @access private
*/
private function _getSearchSpecs($handler = 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;
}
// 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
* @access public
* @throws object PEAR Error
* @return string The requested resource
*/
function getRecord($id)
{
if ($this->debug) {
echo "<pre>Get Record: $id</pre>\n";
}
/** @var Memcache $memCache */
global $memCache;
global $configArray;
$record = $memCache->get("solr_record_$id");
if ($record == false){
// Query String Parameters
$options = array('q' => "id:\"$id\"");
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
if (isset($result['response']['docs'][0])){
$record = $result['response']['docs'][0];
$memCache->set("solr_record_$id", $record, 0, $configArray['Caching']['solr_record']);
}else{
global $logger;
$logger->log("Unable to find record $id in Solr", PEAR_LOG_ERR);
PEAR_Singleton::raiseError("Record not found $id");
}
}
return $record;
}
function getRecordByBarcode($barcode){
if ($this->debug) {
echo "<pre>Get Record by Barcode: $barcode</pre>\n";
}
// Query String Parameters
$options = array('q' => "barcode:\"$barcode\"");
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
return $result['response']['docs'][0];
}
/**
* Retrieves a document specified by the ID.
*
* @param array $ids A list of document to retrieve from Solr
* @access public
* @throws object PEAR Error
* @return string The requested resource
*/
function getRecords($ids)
{
if (count($ids) == 0){
return array();
}
//Solr does not seem to be able to return more than 50 records at a time,
//If we have more than 50 ids, we will ned to make multiple calls and
//concatenate the results.
$records = array();
$startIndex = 0;
$batchSize = 30;
$lastBatch = false;
while (true){
$endIndex = $startIndex + $batchSize;
if ($endIndex >= count($ids)){
$lastBatch = true;
$endIndex = count($ids);
$batchSize = count($ids) - $startIndex;
}
$tmpIds = array_slice($ids, $startIndex, $batchSize);
// Query String Parameters
$idString = '';
foreach ($tmpIds as $id){
if (strlen($idString) > 0){
$idString .= ' OR ';
}
$idString .= "id:\"$id\"";
}
$options = array('q' => $idString, 'rows' => $batchSize);
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
foreach ($result['response']['docs'] as $record){
$records[$record['id']] = $record;
}
if ($lastBatch){
break;
} else{
$startIndex = $endIndex;
}
}
//echo("Found " . count($records) . " records. Should have found " . count($ids) . "\r\n<br/>");
return $records;
}
/**
* Get records similar to one record
* Uses MoreLikeThis Request Handler
*
* Uses SOLR MLT Query Handler
*
* @access public
* @var string $id The id to retrieve similar titles for
* @throws object PEAR Error
* @return array An array of query results
*
*/
function getMoreLikeThis($id)
{
// Query String Parameters
$options = array('q' => "id:$id", 'qt' => 'morelikethis');
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
return $result;
}
/**
* Get records similar to one record
* Uses MoreLikeThis Request Handler
*
* Uses SOLR MLT Query Handler
*
* @access public
* @var string $id The id to retrieve similar titles for
* @var array $originalResult The original record we are getting similar titles for.
* @throws object PEAR Error
* @return array An array of query results
*
*/
function getMoreLikeThis2($id, $originalResult = null)
{
if ($originalResult == null){
$originalResult = $this->getRecord($id);
}
// Query String Parameters
$options = array('q' => "id:$id", 'qt' => 'morelikethis2', 'mlt.interestingTerms' => 'details', 'rows' => 25);
if ($originalResult){
$options['fq'] = array();
if (isset($originalResult['target_audience_full'])){
$options['fq'][] = 'target_audience_full:"' . $originalResult['target_audience_full'] . '"';
}
if (isset($originalResult['literary_form'])){
$options['fq'][] = 'literary_form:"' . $originalResult['literary_form'] . '"';
}
if (isset($originalResult['language'])){
$options['fq'][] = 'language:"' . $originalResult['language'][0] . '"';
}
//Don't want to get other editions of the same work (that's a different query)
if (isset($originalResult['isbn'])){
if (is_array($originalResult['isbn'])){
foreach($originalResult['isbn'] as $isbn){
$options['fq'][] = '-isbn:' . ISBN::normalizeISBN($isbn);
}
}else{
$options['fq'][] = '-isbn:' . ISBN::normalizeISBN($originalResult['isbn']);
}
}
if (isset($originalResult['upc'])){
if (is_array($originalResult['upc'])){
foreach($originalResult['upc'] as $upc){
$options['fq'][] = '-upc:' . ISBN::normalizeISBN($upc);
}
}else{
$options['fq'][] = '-upc:' . ISBN::normalizeISBN($originalResult['upc']);
}
}
}
$searchLibrary = Library::getSearchLibrary();
$searchLocation = Location::getSearchLocation();
$scopingFilters = $this->getScopingFilters($searchLibrary, $searchLocation);
foreach ($scopingFilters as $filter){
$options['fq'][] = $filter;
}
$boostFactors = $this->getBoostFactors($searchLibrary, $searchLocation);
$options['bf'] = $boostFactors;
if (!empty($this->_solrShards) && is_array($this->_solrShards)) {
$options['shards'] = implode(',',$this->_solrShards);
}
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
return $result;
}
/**
* Get records similar to one record
* Uses MoreLikeThis Request Handler
*
* Uses SOLR MLT Query Handler
*
* @access public
* @var string[] $ids A list of ids to return data for
* @throws object PEAR Error
* @return array An array of query results
*
*/
function getMoreLikeThese($ids)
{
// Query String Parameters
$idString = implode(' OR ', $ids);
$options = array('q' => "id:($idString)", 'qt' => 'morelikethese', 'mlt.interestingTerms' => 'details', 'rows' => 25);
$searchLibrary = Library::getSearchLibrary();
$searchLocation = Location::getSearchLocation();
$scopingFilters = $this->getScopingFilters($searchLibrary, $searchLocation);
$options['fq'][] = "-id:($idString)";
foreach ($scopingFilters as $filter){
$options['fq'][] = $filter;
}
$boostFactors = $this->getBoostFactors($searchLibrary, $searchLocation);
$options['bf'] = $boostFactors;
if (!empty($this->_solrShards) && is_array($this->_solrShards)) {
$options['shards'] = implode(',',$this->_solrShards);
}
$result = $this->_select('GET', $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
return $result;
}
/**
* Get record data based on the provided field and phrase.
* Used for AJAX suggestions.
*
* @access public
* @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
*/
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];
}
/**
* Get spelling suggestions based on input phrase.
*
* @access public
* @param string $phrase The input phrase
* @return array An array of spelling suggestions
*/
function checkSpelling($phrase)
{
if ($this->debug) {
echo "<pre>Spell Check: $phrase</pre>\n";
}
// Query String Parameters
$options = array(
'q' => $phrase,
'rows' => 0,
'start' => 1,
'indent' => 'yes',
'spellcheck' => 'true'
);
$result = $this->_select(HTTP_REQUEST_METHOD_GET, $options);
if (PEAR_Singleton::isError($result)) {
PEAR_Singleton::raiseError($result);
}
return $result;
}
/**
* applySearchSpecs -- internal method to build query string from search parameters
*
* @access private
* @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
* @throws object PEAR Error
* @static
* @return string A search string suitable for adding to a query URL
*/
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
$searchString = '(' . $this->_applySearchSpecs($clauseArray, $values, $internalJoin) . ')';
// ...and add a weight if we have one
$weight = $sw[1];
if(!is_null($weight) && $weight && $weight > 0) {
$searchString .= '^' . $weight;
}
// push it onto the stack of clauses
$clauses[] = $searchString;
} else {
// Otherwise, we've got a (list of) [munge, weight] pairs to deal with
foreach ($clauseArray as $spec) {
// build a string like title:("one two")
$searchString = $field . ':(' . $values[$spec[0]] . ')';
// Add the weight it we have one. Yes, I know, it's redundant code.
$weight = $spec[1];
if(!is_null($weight) && $weight && $weight > 0) {
$searchString .= '^' . $weight;
}
// ..and push it on the stack of clauses
$clauses[] = $searchString;
}
}
}
// Join it all together
return implode(' ' . $joiner . ' ', $clauses);
}
/**
* Load Boost factors for a query
*
* @param Library $searchLibrary
* @param Location $searchLocation
* @return array
*/
public function getBoostFactors($searchLibrary, $searchLocation)
{
$boostFactors = array();
global $language;
if ($language == 'es') {
$boostFactors[] = 'language_boost_es';
} else {
$boostFactors[] = 'language_boost';
}
$applyHoldingsBoost = true;
if (isset($searchLibrary) && !is_null($searchLibrary)) {
$applyHoldingsBoost = $searchLibrary->applyNumberOfHoldingsBoost;
}
if ($applyHoldingsBoost) {
$boostFactors[] = 'product(num_holdings,15,div(format_boost,50))';
} else {
$boostFactors[] = 'product(15,div(format_boost,50))';
}
//$boostFactors[] = 'product(num_holdings,7)';
//Add rating as part of the ranking, normalize so ratings of less that 2.5 are below unrated entries.
$boostFactors[] = 'product(sum(abs(rating),-2.5),10)';
if (isset($searchLibrary) && !is_null($searchLibrary) && $searchLibrary->boostByLibrary == 1) {
$boostFactors[] = "lib_boost_{$searchLibrary->subdomain}";
}
if (isset($searchLocation) && !is_null($searchLocation) && $searchLocation->boostByLocation == 1) {
$boostFactors[] = "loc_boost_{$searchLocation->code}";
}
return $boostFactors;
}
/**
* Given a field name and search string, return an array containing munged
* versions of the search string for use in _applySearchSpecs().
*
* @access private
* @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
*/
private function _buildMungeValues($lookfor, $custom = null, $basic = true)
{
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['exact'] = $lookfor;
$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.
$onephrase = strstr($lookfor, '"') ? $lookfor : '"' . $lookfor . '"';
$values = array('exact' => $onephrase, 'onephrase' => $onephrase, 'and' => $lookfor, 'or' => $lookfor);
}
// Apply custom munge operations if necessary:
if (is_array($custom) && $basic) {
foreach($custom as $mungeName => $mungeOps) {
$values[$mungeName] = $lookfor;
// Skip munging if tokenization is disabled.
foreach($mungeOps as $operation) {
switch($operation[0]) {
case 'exact':
$values[$mungeName] = '"' . $values[$mungeName] . '"';
break;
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).
*
* @access private
* @param string $field The YAML search spec field name to search
* @param string $lookfor The string to search for in the field
* @param bool $tokenize Should we tokenize $lookfor or pass it through?
* @return string The query
*/
private function _buildQueryComponent($field, $lookfor, $tokenize = true)
{
// Load the YAML search specifications:
$ss = $this->_getSearchSpecs($field);
// 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 . ')';
}
// Munge the user query in a few different ways:
$customMunge = isset($ss['CustomMunge']) ? $ss['CustomMunge'] : null;
$values = $this->_buildMungeValues($lookfor, $customMunge, $tokenize);
// 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).
*
* @access private
* @param string $handler The handler for the search
* @param string $query The string to search for in the field
* @return string The query
*/
private function _buildAdvancedQuery($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
// $tokenize 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
*
* @access public
* @param array $search An array of search parameters
* @throws object PEAR Error
* @static
* @return string The query
*/
function buildQuery($search)
{
$groups = array();
$excludes = array();
$query = '';
if (is_array($search)) {
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 = SolrUtils::capitalizeBooleans($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.
* @access private
*/
private function _normalizeSort($sort)
{
// Break apart sort into field name and sort direction (note error
// suppression to prevent notice when direction is left blank):
@list($sortField, $sortDirection) = explode(' ', $sort);
// Default sort order (may be overridden by switch below):
$defaultSortDirection = 'asc';
// Translate special sort values into appropriate Solr fields:
switch ($sortField) {
case 'year':
case 'publishDate':
$sortField = 'publishDateSort';
$defaultSortDirection = 'desc';
break;
case 'author':
$sortField = 'authorStr';
break;
case 'title':
$sortField = 'title_sort';
break;
}
// Normalize sort direction to either "asc" or "desc":
$sortDirection = strtolower(trim($sortDirection));
if ($sortDirection != 'desc' && $sortDirection != 'asc') {
$sortDirection = $defaultSortDirection;
}
return $sortField . ' ' . $sortDirection;
}
function disableScoping(){
$this->scopingDisabled = true;
global $configArray;
if (isset($configArray['ShardPreferences']['defaultChecked']) && !empty($configArray['ShardPreferences']['defaultChecked']) ) {
$checkedShards = $configArray['ShardPreferences']['defaultChecked'];
$shards = is_array($checkedShards) ? $checkedShards : array($checkedShards);
} else {
// If no default is configured, use all shards...
$shards = array_keys($configArray['IndexShards']);
}
$this->_loadShards($shards);
}
function enableScoping(){
$this->scopingDisabled = false;
global $configArray;
if (isset($configArray['ShardPreferences']['defaultChecked']) && !empty($configArray['ShardPreferences']['defaultChecked']) ) {
$checkedShards = $configArray['ShardPreferences']['defaultChecked'];
$shards = is_array($checkedShards) ? $checkedShards : array($checkedShards);
} else {
// If no default is configured, use all shards...
$shards = array_keys($configArray['IndexShards']);
}
$this->_loadShards($shards);
}
/**
* Execute a search.