forked from Aspen-Discovery/aspen-discovery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseSearcher.php
2808 lines (2573 loc) · 80.3 KB
/
BaseSearcher.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
require_once ROOT_DIR . '/sys/SearchEntry.php';
require_once ROOT_DIR . '/sys/Recommend/RecommendationFactory.php';
/**
* Search Object abstract base class.
*
* Generic base class for abstracting search URL generation and other standard
* functionality. This should be extended to implement functionality for specific
* modules (Grouped Works, Lists, OAI, Archives, etc)
*/
abstract class SearchObject_BaseSearcher {
// Parsed query
protected $query = null;
// SEARCH PARAMETERS
// RSS feed?
protected $view = null;
protected $defaultView = 'list';
// Search terms
protected $searchTerms = [];
// Sorting
protected $sort = null;
protected $defaultSort = 'relevance';
protected $defaultSortByType = [];
/** @var string */
protected $searchSource = 'local';
// Filters
protected $filterList = [];
// Facets information
protected $allFacetSettings = [];
// Page number
protected $page = 1;
// Result limit
protected $limit = 20;
// Used to pass hidden filter queries to Solr
protected $hiddenFilters = [];
//Limiters applied to the search
protected $limiters = [];
// STATS
protected $resultsTotal = 0;
// OTHER VARIABLES
// Module and Action for building search results URLs
protected $resultsModule = 'Search';
protected $resultsAction = 'Results';
// Facets information
protected $facetConfig; // Array of valid facet fields=>labels
protected $facetOptions = [];
// Available sort options
protected $sortOptions = [];
// An ID number for saving/retrieving search
protected $searchId = null;
protected $savedSearch = false;
protected $searchType = 'basic';
// Possible values of $searchType:
protected $isAdvanced = false;
protected $basicSearchType = 'basic';
protected $advancedSearchType = 'advanced';
// Flag for logging/search history
protected $disableLogging = false;
protected $isPrimarySearch = false;
// Search options for the user
protected $advancedTypes = [];
protected $searchIndexes = [];
// Recommendation modules associated with the search:
/** @var bool|array $recommend */
protected $recommend = false;
// STATS
protected $initTime = null;
protected $endTime = null;
protected $totalTime = null;
protected $queryStartTime = null;
protected $queryEndTime = null;
protected $queryTime = null;
/**
* Constructor. Initialise some details about the server
*
* @access public
*/
public function __construct() {
global $timer;
$timer->logTime('Setup Base Search Object');
}
function ping($forceCheck) {
return true;
}
/* Parse apart the field and value from a URL filter string.
*
* @access protected
* @param string $filter A filter string from url : "field:value"
* @return array Array with elements 0 = field, 1 = value.
*/
protected function parseFilter($filter) {
if ((strpos($filter, ' AND ') !== FALSE) || (strpos($filter, ' OR ') !== FALSE)) {
//This is a complex filter that does not need parsing
return [
'',
$filter,
];
}
// Split the string
$temp = explode(':', $filter);
// $field is the first value
$field = array_shift($temp);
// join them in case the value contained colons as well.
$value = join(":", $temp);
// Remove quotes from the value if there are any
if (substr($value, 0, 1) == '"') {
$value = substr($value, 1);
}
if (substr($value, -1, 1) == '"') {
$value = substr($value, 0, -1);
}
// One last little clean on whitespace
$value = trim($value);
// Send back the results:
return [
$field,
$value,
];
}
/**
* @return string
*/
public function getSearchSource() {
return $this->searchSource;
}
public abstract function getEngineName();
/**
* @return array
*/
public function getHiddenFilters() {
return $this->hiddenFilters;
}
/**
* Does the object already contain the specified filter?
*
* @access public
* @param string $filterName The name of the filter
* @param string $value The value of the filter
* @return bool
*/
public function hasFilter($filterName, $value) {
if (isset($this->filterList[$filterName]) && in_array($value, $this->filterList[$filterName])) {
return true;
}
return false;
}
public function clearFilters() {
$this->filterList = [];
}
public function setAppliedFilters($filterList) {
$this->filterList = $filterList;
}
/**
* Take a filter string and add it into the protected
* array checking for duplicates.
*
* @access public
* @param string|array $newFilter A filter string from url : "field:value"
*/
public function addFilter($newFilter) {
if (is_array($newFilter)) {
$field = $newFilter[0];
$value = $newFilter[1];
} else {
if (strlen($newFilter) == 0) {
return;
}
// Extract field and value from URL string:
[
$field,
$value,
] = $this->parseFilter($newFilter);
}
if ($field == '') {
$field = count($this->filterList) + 1;
}
// Check for duplicates -- if it's not in the array, we can add it
if (!$this->hasFilter($field, $value)) {
if (!is_numeric($field)) {
if ($field === 'literary-form') {
$field = 'literary_form';
} elseif ($field === 'literary-form-full') {
$field = 'literary_form_full';
} elseif ($field === 'target-audience') {
$field = 'target_audience';
} elseif ($field === 'target-audience-full') {
$field = 'target_audience_full';
}
$field = $this->getScopedFieldName($field);
}
$this->filterList[$field][] = $value;
}
}
/**
* Remove a filter from the list.
*
* @access public
* @param string $oldFilter A filter string from url : "field:value"
*/
public function removeFilter($oldFilter) {
// Extract field and value from URL string:
[
$field,
$value,
] = $this->parseFilter($oldFilter);
// Make sure the field exists
if (isset($this->filterList[$field])) {
// Loop through all filters on the field
foreach ($this->filterList[$field] as $key => $existingValue) {
// Does it contain the value we don't want?
if ($existingValue == $value) {
// If so remove it.
unset($this->filterList[$field][$key]);
}
}
}
}
public function removeFilterByPrefix($fieldName) {
// Make sure the field exists
$scopedName = $this->getScopedFieldName($fieldName);
if (isset($this->filterList[$scopedName])) {
// If so remove it.
unset($this->filterList[$scopedName]);
}
}
public function clearHiddenFilters() {
$this->hiddenFilters = [];
}
public function addHiddenFilter($field, $value) {
$this->hiddenFilters[] = $field . ':' . $value;
}
/**
* Get a user-friendly string to describe the provided facet field.
*
* @access protected
* @param string $field Facet field name.
* @return string Human-readable description of field.
*/
protected function getFacetLabel($field) {
$shortField = $field;
$shortField = $this->getUnscopedFieldName($shortField);
$facetConfig = $this->getFacetConfig();
if (isset($facetConfig[$field])) {
$facetConfig = $facetConfig[$field];
if ($facetConfig instanceof FacetSetting) {
return $facetConfig->displayName;
} else {
return $facetConfig;
}
} elseif (isset($facetConfig[$shortField])) {
$facetConfig = $facetConfig[$shortField];
if ($facetConfig instanceof FacetSetting) {
return $facetConfig->displayName;
} else {
return $facetConfig;
}
} else {
return ucwords(str_replace("_", " ", translate([
'text' => $shortField,
'isPublicFacing' => true,
])));
}
}
/**
* Clear all facets which will speed up searching if we won't be using the facets.
*/
public function clearFacets() {
$this->facetConfig = [];
}
public function hasAppliedFacets() {
return count($this->filterList) > 0;
}
/**
* Return an array structure containing all current filters
* and urls to remove them.
*
* @access public
* @return array Field, values and removal urls
*/
public function getFilterList() {
$list = [];
$facetConfig = $this->getFacetConfig();
// Loop through all the current filter fields
foreach ($this->filterList as $field => $values) {
// and each value currently used for that field
$translate = false;
if (isset($facetConfig[$field])) {
if (is_object($facetConfig[$field])) {
$translate = $facetConfig[$field]->translate;
} else {
if (!empty($facetConfig['translated_facets'])) {
$translate = in_array($field, $facetConfig['translated_facets']);
}
}
}
$facetLabel = $this->getFacetLabel($field);
foreach ($values as $value) {
if ($field == 'available_at' && $value == '*') {
$anyLocationLabel = $this->getFacetSetting("Availability", "anyLocationLabel");
$display = $anyLocationLabel == '' ? "Any Marmot Location" : $anyLocationLabel;
} elseif ($field == 'available_at' && $value == '*') {
$anyLocationLabel = $this->getFacetSetting("Availability", "anyLocationLabel");
$display = $anyLocationLabel == '' ? "Any Marmot Location" : $anyLocationLabel;
} elseif ($field == 'start_date') {
$filterValue = substr($value, strpos($value, '[') + 1);
$filterValue = substr($filterValue, 0, -2);
$range = explode(' TO ', $filterValue);
$utcTimeZone = new DateTimeZone('UTC');
$defaultTimezone = new DateTimeZone(date_default_timezone_get());
if ($range[0] != '*') {
$dt = new DateTime($range[0], $utcTimeZone);
$dt->setTimezone($defaultTimezone);
$startDate = $dt->format("m/d/Y");
}else{
$startDate = '';
}
if ($range[1] != '*') {
$dt = new DateTime($range[1], $utcTimeZone);
$dt->setTimezone($defaultTimezone);
$endDate = $dt->format("m/d/Y");
}else{
$endDate = '';
}
if (empty($startDate)) {
$display = translate(['text'=>'Before %1%', 1=>$endDate, 'isPublicFacing'=>true]);
}else if (empty($endDate)) {
$display = translate(['text'=>'After %1%', 1=>$startDate, 'isPublicFacing'=>true]);
}else{
$display = translate(['text'=>'Between %1% and %2%', 1=>$startDate, 2=>$endDate, 'isPublicFacing'=>true]);
}
} else {
$display = $translate ? translate([
'text' => $value,
'isPublicFacing' => true,
'escape' => true,
]) : $value;
}
$list[$facetLabel][] = [
'value' => $value,
// raw value for use with Solr
'display' => $display,
// version to display to user
'field' => $field,
'removalUrl' => $this->renderLinkWithoutFilter("$field:$value"),
'countIsApproximate' => false,
];
}
}
return $list;
}
/**
* Return the specified setting from the configuration file.
*
* @access public
* @param string $section The section of the configuration file to look at.
* @param string $setting The setting within the specified file to return.
* @return string The value of the setting (blank if none).
*/
public function getFacetSetting($section, $setting) {
return isset($this->allFacetSettings[$section][$setting]) ? $this->allFacetSettings[$section][$setting] : '';
}
/**
* Return a url for the current search with an additional filter
*
* @access public
* @param string $field The name of the field to filter on
* @param string $filterValue The value to filter on
* @return string URL of a new search
*/
public function renderLinkWithFilter($field, $filterValue) {
// Stash our old data for a minute
$oldFilterList = $this->filterList;
$oldPage = $this->page;
// Availability facet can have only one item selected at a time
$disallowReplacements = false;
if (strpos($field, 'availability_toggle') === 0) {
foreach ($this->filterList as $name => $value) {
if (strpos($name, 'availability_toggle') === 0) {
unset ($this->filterList[$name]);
$disallowReplacements = true;
}
}
}
// Add the new filter
if ($filterValue != null) {
$this->addFilter([
$field,
$filterValue,
]);
}
// Remove page number
$this->page = 1;
// Get the new url
$url = $this->renderSearchUrl();
// Restore the old data
$this->filterList = $oldFilterList;
$this->page = $oldPage;
if ($disallowReplacements) {
$url .= '&disallowReplacements';
}
// Return the URL
return $url;
}
/**
* Return a url for the current search without one of the current filters
*
* @access public
* @param string $oldFilter A filter to remove from the search url
* @return string URL of a new search
*/
public function renderLinkWithoutFilter($oldFilter) {
return $this->renderLinkWithoutFilters([$oldFilter]);
}
/**
* Return a url for the current search without several of the current filters
*
* @access public
* @param array $filters The filters to remove from the search url
* @return string URL of a new search
*/
public function renderLinkWithoutFilters($filters) {
// Stash our old data for a minute
$oldFilterList = $this->filterList;
$oldPage = $this->page;
// Remove the old filter
foreach ($filters as $oldFilter) {
$this->removeFilter($oldFilter);
}
// Remove page number
$this->page = 1;
// Get the new url
$url = $this->renderSearchUrl();
// Restore the old data
$this->filterList = $oldFilterList;
$this->page = $oldPage;
// Return the URL
return $url;
}
/**
* Get the base URL for search results (including ? parameter prefix).
*
* @access protected
* @return string Base URL
*/
protected function getBaseUrl() {
return "/{$this->resultsModule}/{$this->resultsAction}?";
}
/**
* Get the URL to load a saved search from the current module.
*
* @access public
* @param string $id The Id of the saved search
* @return string Saved search URL.
*/
public function getSavedUrl($id) {
return $this->getBaseUrl() . 'saved=' . urlencode($id);
}
/**
* Get an array of strings to attach to a base URL in order to reproduce the
* current search.
*
* @access protected
* @return array Array of URL parameters (key=url_encoded_value format)
*/
protected function getSearchParams() {
$params = [];
switch ($this->searchType) {
// Advanced search
case $this->advancedSearchType:
if (false) {
// Advanced Search Pop-up (probably)
// structure lookfor[]
$paramIndex = 0;
for ($i = 0; $i < count($this->searchTerms); $i++) {
for ($j = 0; $j < count($this->searchTerms[$i]['group']); $j++) {
$paramIndex++;
$params[] = "lookfor[$paramIndex]=" . urlencode($this->searchTerms[$i]['group'][$j]['lookfor']);
$params[] = "searchType[$paramIndex]=" . urlencode($this->searchTerms[$i]['group'][$j]['field']);
$params[] = "join[$paramIndex]=" . urlencode($this->searchTerms[$i]['group'][$j]['bool']);
}
if ($i > 0) {
$params[] = "groupEnd[$paramIndex]=1";
}
}
} else {
// Advanced Search Page
//structure lookfor0[], lookfor1[],
$params[] = "join=" . urlencode($this->searchTerms[0]['join']);
for ($i = 0; $i < count($this->searchTerms); $i++) {
$params[] = "bool" . $i . "[]=" . urlencode($this->searchTerms[$i]['group'][0]['bool']);
for ($j = 0; $j < count($this->searchTerms[$i]['group']); $j++) {
$params[] = "lookfor" . $i . "[]=" . urlencode($this->searchTerms[$i]['group'][$j]['lookfor']);
$params[] = "type" . $i . "[]=" . urlencode($this->searchTerms[$i]['group'][$j]['field']);
}
}
}
break;
// Basic search
default:
if (isset($this->searchTerms[0]['lookfor'])) {
$params[] = "lookfor=" . urlencode($this->searchTerms[0]['lookfor']);
}
if (isset($this->searchTerms[0]['index'])) {
if (
$this->searchType == 'basic' ||
$this->searchType == 'ebsco_eds' ||
$this->searchType = 'summon'
) {
$params[] = "searchIndex=" . urlencode($this->searchTerms[0]['index']);
} else {
$params[] = "type=" . urlencode($this->searchTerms[0]['index']);
}
}
break;
}
return $params;
}
/**
* Initialize the object's search settings for a basic search found in the
* $_REQUEST super global.
*
* @access public
* @param String|String[] $searchTerm
* @return boolean True if search settings were found, false if not.
*/
public function initBasicSearch($searchTerm = null) {
require_once ROOT_DIR . '/sys/Utils/StringUtils.php';
if ($searchTerm == null) {
// If no lookfor parameter was found, we have no search terms to
// add to our array!
if (!isset($_REQUEST['lookfor'])) {
return false;
} else {
$searchTerm = StringUtils::removeTrailingPunctuation(trim($_REQUEST['lookfor']));
}
} else {
$searchTerm = StringUtils::removeTrailingPunctuation(trim($searchTerm));
}
// If no type defined use default
if ((isset($_REQUEST['searchIndex'])) && ($_REQUEST['searchIndex'] != '')) {
$type = $_REQUEST['searchIndex'];
// Flatten type arrays for backward compatibility:
if (is_array($type)) {
$type = strip_tags($type[0]);
} else {
$type = strip_tags($type);
}
//The type should never have punctuation in it (quotes, colons, etc)
$type = preg_replace('/[:"\']/', '', $type);
if (!array_key_exists($type, $this->getSearchIndexes()) && !array_key_exists($type, $this->advancedTypes)) {
$type = $this->getDefaultIndex();
}
} else {
$type = $this->getDefaultIndex();
}
if (strpos($searchTerm, ':') > 0) {
$tempSearchInfo = explode(':', $searchTerm);
if (count($tempSearchInfo) == 2) {
//Check for leading and trailing parentheses
if (strlen($tempSearchInfo[0]) > 0 && $tempSearchInfo[0][0] == '(') {
$tempSearchInfo[0] = substr($tempSearchInfo[0], 1);
}
if (strlen($tempSearchInfo[1]) > 0 && $tempSearchInfo[1][-1] == ')') {
$tempSearchInfo[1] = substr($tempSearchInfo[1], 0, -1);
}
if (array_key_exists($tempSearchInfo[0], $this->searchIndexes)) {
$type = $tempSearchInfo[0];
$searchTerm = $tempSearchInfo[1];
} else {
$validFields = $this->loadValidFields();
if (is_null($validFields)) {
$validFields = [];
}
$dynamicFields = $this->loadDynamicFields();
if (is_null($dynamicFields)) {
$dynamicFields = [];
}
if (!in_array($tempSearchInfo[0], $validFields) && !in_array($tempSearchInfo[0], $dynamicFields) || array_key_exists($tempSearchInfo[0], $this->advancedTypes)) {
$searchTerm = str_replace(':', ' ', $searchTerm);
} else {
return false;
}
}
} else {
//This is an advanced search
return false;
}
}
$this->searchTerms[] = [
'index' => $type,
'lookfor' => $searchTerm,
];
if (isset($_REQUEST['searchId']) && is_numeric($_REQUEST['searchId'])) {
$searchEntry = new SearchEntry();
$searchEntry->id = $_REQUEST['searchId'];
if ($searchEntry->find(true)) {
$activeUserId = UserAccount::getActiveUserId();
if ($activeUserId && ($activeUserId == $searchEntry->user_id)) {
$this->searchId = $searchEntry->id;
$this->savedSearch = $searchEntry->saved;
} elseif ($searchEntry->session_id == session_id()) {
$this->searchId = $searchEntry->id;
$this->savedSearch = $searchEntry->saved;
}
}
}
return true;
}
/**
* Initialize the object's search settings for a basic search found in the
* $_REQUEST super global.
*
* @access public
* @param String $searchIndex
* @param String $searchTerm
* @return boolean True if search settings were found, false if not.
*/
public function initBasicSearchWithIndex($searchIndex, $searchTerm) {
require_once ROOT_DIR . '/sys/Utils/StringUtils.php';
$searchTerm = StringUtils::removeTrailingPunctuation(trim($searchTerm));
$type = $searchIndex;
// Flatten type arrays for backward compatibility:
if (is_array($type)) {
$type = strip_tags($type[0]);
} else {
$type = strip_tags($type);
}
//The type should never have punctuation in it (quotes, colons, etc)
$type = preg_replace('/[:"\']/', '', $type);
if (!array_key_exists($type, $this->getSearchIndexes()) && !array_key_exists($type, $this->advancedTypes)) {
$type = $this->getDefaultIndex();
}
if (strpos($searchTerm, ':') > 0) {
$tempSearchInfo = explode(':', $searchTerm);
if (count($tempSearchInfo) == 2) {
//Check for leading and trailing parentheses
if (strlen($tempSearchInfo[0]) > 0 && $tempSearchInfo[0][0] == '(') {
$tempSearchInfo[0] = substr($tempSearchInfo[0], 1);
}
if (strlen($tempSearchInfo[1]) > 0 && $tempSearchInfo[1][-1] == ')') {
$tempSearchInfo[1] = substr($tempSearchInfo[1], 0, -1);
}
if (array_key_exists($tempSearchInfo[0], $this->searchIndexes)) {
$type = $tempSearchInfo[0];
$searchTerm = $tempSearchInfo[1];
} else {
$validFields = $this->loadValidFields();
$dynamicFields = $this->loadDynamicFields();
if (!in_array($tempSearchInfo[0], $validFields) && !in_array($tempSearchInfo[0], $dynamicFields) || array_key_exists($tempSearchInfo[0], $this->advancedTypes)) {
$searchTerm = str_replace(':', ' ', $searchTerm);
} else {
return false;
}
}
} else {
//This is an advanced search
return false;
}
}
$this->searchTerms = [];
$this->searchTerms[] = [
'index' => $type,
'lookfor' => $searchTerm,
];
return true;
}
public function setSearchTerms($searchTerms) {
$this->clearQuery();
$this->searchTerms = [];
$this->searchTerms[] = $searchTerms;
}
public function isAdvanced() {
return $this->isAdvanced;
}
/**
* Initialize the object's search settings for an advanced search found in the
* $_REQUEST super global. Advanced searches have numeric subscripts on the
* lookfor and type parameters -- this is how they are distinguished from basic
* searches.
*
* @access protected
*/
protected function initAdvancedSearch() {
$this->isAdvanced = true;
$this->searchType = $this->advancedSearchType;
if (isset($_REQUEST['lookfor'])) {
if (is_array($_REQUEST['lookfor'])) {
//Advanced search from popup form
$this->searchType = $this->advancedSearchType;
$group = [];
foreach ($_REQUEST['lookfor'] as $index => $lookfor) {
$group[] = [
'field' => $_REQUEST['searchType'][$index],
'lookfor' => $lookfor,
'bool' => $_REQUEST['join'][$index],
];
if (isset($_REQUEST['groupEnd'])) {
if (isset($_REQUEST['groupEnd'][$index]) && $_REQUEST['groupEnd'][$index] == 1) {
// Add the completed group to the list
$this->searchTerms[] = [
'group' => $group,
'join' => $_REQUEST['join'][$index],
];
$group = [];
}
}
}
if (count($group) > 0 && !empty($index)) {
// Add the completed group to the list
$this->searchTerms[] = [
'group' => $group,
'join' => $_REQUEST['join'][$index],
];
}
} else {
if (strpos($_REQUEST['lookfor'], ':') > 0) {
$tempSearchInfo = explode(':', $_REQUEST['lookfor']);
if (count($tempSearchInfo) == 2) {
//Check for leading and trailing parentheses
if ($tempSearchInfo[0][0] == '(') {
$tempSearchInfo[0] = substr($tempSearchInfo[0], 1);
}
if ($tempSearchInfo[1][-1] == ')') {
$tempSearchInfo[1] = substr($tempSearchInfo[1], 0, -1);
}
$validFields = $this->loadValidFields();
$dynamicFields = $this->loadDynamicFields();
if (in_array($tempSearchInfo[0], $validFields) || in_array($tempSearchInfo[0], $dynamicFields) || array_key_exists($tempSearchInfo[0], $this->advancedTypes)) {
$group[] = [
'field' => $tempSearchInfo[0],
'lookfor' => $tempSearchInfo[1],
'bool' => 'AND',
];
} else {
$group[] = [
'field' => $this->getDefaultIndex(),
'lookfor' => str_replace(':', ' ', $_REQUEST['lookfor']),
'bool' => 'AND',
];
}
$this->searchTerms[] = [
'group' => $group,
'join' => 'AND',
];
} else {
//TODO: This needs to create multiple groups for the search.
preg_match_all('~((\w+?):("?.+?"?)(AND|OR|\)|$))~', $_REQUEST['lookfor'], $matches, PREG_SET_ORDER);
if (!empty($matches)) {
foreach ($matches as $match) {
$group[] = [
'field' => $match[2],
'lookfor' => str_replace(':', ' ', $match[3]),
'bool' => ($match[4] == ')') ? 'AND' : $match[4],
];
}
}else{
$group[] = [
'field' => $this->getDefaultIndex(),
'lookfor' => str_replace(':', ' ', $_REQUEST['lookfor']),
'bool' => 'AND',
];
}
$this->searchTerms[] = [
'group' => $group,
'join' => 'AND',
];
}
}
}
} else {
//********************
// Advanced Search logic
// 'lookfor0[]' 'type0[]'
// 'lookfor1[]' 'type1[]' ...
$this->searchType = $this->advancedSearchType;
$groupCount = 0;
// Loop through each search group
while (isset($_REQUEST['lookfor' . $groupCount])) {
$group = [];
// Loop through each term inside the group
for ($i = 0, $l = count($_REQUEST['lookfor' . $groupCount]); $i < $l; $i++) {
// Ignore advanced search fields with no lookup
if ($_REQUEST['lookfor' . $groupCount][$i] != '') {
// Use default fields if not set
if (!empty($_REQUEST['type' . $groupCount][$i])) {
$type = strip_tags($_REQUEST['type' . $groupCount][$i]);
} else {
$type = $this->getDefaultIndex();
}
//Marmot - search both ISBN-10 and ISBN-13
//Check to see if the search term looks like an ISBN10 or ISBN13
$lookfor = strip_tags($_REQUEST['lookfor' . $groupCount][$i]);
// Add term to this group
$group[] = [
'field' => $type,
'lookfor' => $lookfor,
'bool' => isset($_REQUEST['bool' . $groupCount]) ? strip_tags($_REQUEST['bool' . $groupCount][0]) : 'AND',
];
}
}
// Make sure we aren't adding groups that had no terms
if (count($group) > 0) {
// Add the completed group to the list
$this->searchTerms[] = [
'group' => $group,
'join' => isset($_REQUEST['join']) ? (is_array($_REQUEST['join']) ? strip_tags(reset($_REQUEST['join'])) : strip_tags($_REQUEST['join'])) : 'AND',
];
}
// Increment
$groupCount++;
}
// Finally, if every advanced row was empty
if (empty($this->searchTerms)) {
// Treat it as an empty basic search
$this->searchType = $this->basicSearchType;
$this->searchTerms[] = [
'index' => $this->getDefaultIndex(),
'lookfor' => '',
];
}
}
}
/**
* Add view mode to the object based on the $_REQUEST super global.
*
* @access protected
*/
protected function initView() {
if (!empty($this->view)) { //return view if it has already been set.
return;
}
// Check for a view parameter in the url.
if (isset($_REQUEST['view'])) {
if ($_REQUEST['view'] == 'rss') {
// we don't want to store rss in the Session variable
$this->view = 'rss';
} elseif ($_REQUEST['view'] == 'excel') {
// we don't want to store excel in the Session variable
$this->view = 'excel';
} elseif ($_REQUEST['view'] == 'ris') {
$this->view = 'ris';
$_SESSION['lastView'] = $this->view;
} else {
// store non-rss views in Session for persistence
$validViews = $this->getViewOptions();
// make sure the url parameter is a valid view
// if (in_array($_REQUEST['view'], array_keys($validViews))) {
if (in_array($_REQUEST['view'], $validViews)) { // currently using a simple array listing the views (not listed in the keys)
$this->view = $_REQUEST['view'];
$_SESSION['lastView'] = $this->view;
} else {
$this->view = $this->defaultView;
}
}
} elseif (isset($_SESSION['lastView']) && !empty($_SESSION['lastView'])) {
// if there is nothing in the URL, check the Session variable
$this->view = $_SESSION['lastView'];
} else {
// otherwise load the default
$this->view = $this->defaultView;
}
}
/**
* Add page number to the object based on the $_REQUEST super global.
*
* @access protected
*/
protected function initPage() {
if (isset($_REQUEST['page'])) {
$page = $_REQUEST['page'];
if (is_array($page)) {
$page = array_pop($page);
}
$this->page = strip_tags($page);
}
$this->page = intval($this->page);
if ($this->page < 1) {
$this->page = 1;
}
}
function setPage($page) {
$this->page = intval($page);
if ($this->page < 1) {
$this->page = 1;
}
}
/**
* Add sort value to the object based on the $_REQUEST super global.
*
* @access protected
*/
protected function initSort() {
$defaultSort = '';
if (isset($_REQUEST['sort'])) {
if (is_array($_REQUEST['sort'])) {
$sort = array_pop($_REQUEST['sort']);
} else {
$sort = $_REQUEST['sort'];
}
$this->sort = $sort;
} elseif ($defaultSort != '') {
$this->sort = $defaultSort;
} else {
// Is there a search-specific sort type set?
$type = isset($_REQUEST['searchIndex']) ? $_REQUEST['searchIndex'] : false;
if ($type && isset($this->defaultSortByType[$type])) {
$this->sort = $this->defaultSortByType[$type];
// If no search-specific sort type was found, use the overall default:
} else {
$this->sort = $this->defaultSort;
}
}
//Validate the sort to make sure it is correct.
if (!array_key_exists($this->sort, $this->getSortOptions())) {
$this->sort = $this->defaultSort;
}