Completed
Push — dev2 ( c285ca...92da4c )
by Gordon
03:10
created

setMoreLikeThisParamsFromRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 9

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4286
cc 1
eloc 9
nc 1
nop 1
1
<?php
2
3
use Elastica\Document;
4
use Elastica\Query;
5
use \SilverStripe\Elastica\ResultList;
6
use Elastica\Query\QueryString;
7
use Elastica\Aggregation\Filter;
8
use Elastica\Filter\Term;
9
use Elastica\Filter\BoolAnd;
10
use Elastica\Aggregation\Terms;
11
use Elastica\Query\Filtered;
12
use Elastica\Query\Range;
13
use \SilverStripe\Elastica\ElasticSearcher;
14
use \SilverStripe\Elastica\Searchable;
15
use \SilverStripe\Elastica\QueryGenerator;
16
use \SilverStripe\Elastica\ElasticaUtil;
17
18
class ElasticSearchPage_Controller extends Page_Controller {
19
20
	private static $allowed_actions = array('SearchForm', 'submit', 'index', 'similar');
21
22
	public function init() {
23
		parent::init();
24
25
		Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
26
		Requirements::javascript("elastica/javascript/jquery.autocomplete.js");
27
		Requirements::javascript("elastica/javascript/elastica.js");
28
		Requirements::css("elastica/css/elastica.css");
29
30
		$this->SearchPage = Controller::curr()->dataRecord;
31
	}
32
33
34
35
	/*
36
	Find DataObjects in Elasticsearch similar to the one selected.  Note that aggregations are not
37
	taken into account, merely the text of the selected document.
38
	 */
39
	public function similar() {
40
		//FIXME double check security, ie if escaping needed
41
		$class = $this->request->param('ID');
42
		$instanceID = $this->request->param('OtherID');
43
44
		$data = $this->initialiseDataArray();
45
46
		$es = $this->primeElasticSearcherFromRequest();
47
48
		$this->setMoreLikeThisParamsFromRequest($es);
49
		$es->setPageLength($this->SearchPage->ResultsPerPage);
50
51
		// filter by class or site tree
52
		if($this->SearchPage->SiteTreeOnly) {
53
			T7; //FIXME test missing
54
			$es->addFilter('IsInSiteTree', true);
55
		} else {
56
			$es->setClasses($this->SearchPage->ClassesToSearch);
57
		}
58
59
		// get the edited fields to search from the database for this search page
60
		// Convert this into a name => weighting array
61
		$fieldsToSearch = array();
62
		$editedSearchFields = $this->ElasticaSearchableFields()->filter(array(
63
			'Active' => true,
64
			'SimilarSearchable' => true
65
		));
66
67
		foreach($editedSearchFields->getIterator() as $searchField) {
68
			$fieldsToSearch[$searchField->Name] = $searchField->Weight;
69
		}
70
71
		// Use the standard field for more like this, ie not stemmed
72
		foreach($fieldsToSearch as $field => $value) {
73
			$fieldsToSearch[$field . '.standard'] = $value;
74
			unset($fieldsToSearch[$field]);
75
		}
76
77
		try {
78
			// Simulate server being down for testing purposes
79
			if($this->request->getVar('ServerDown')) {
80
				throw new Elastica\Exception\Connection\HttpException('Unable to reach search server');
81
			}
82
			if(class_exists($class)) {
83
				$instance = \DataObject::get_by_id($class, $instanceID);
84
85
				$paginated = $es->moreLikeThis($instance, $fieldsToSearch);
86
87
				$this->Aggregations = $es->getAggregations();
88
				$this->successfulSearch($data, $paginated);
89
				$data['SimilarTo'] = $instance;
90
91
92
				$moreLikeThisTerms = $paginated->getList()->MoreLikeThisTerms;
93
				$fieldToTerms = new ArrayList();
94
				foreach(array_keys($moreLikeThisTerms) as $fieldName) {
95
					$readableFieldName = str_replace('.standard', '', $fieldName);
96
					$fieldTerms = new ArrayList();
97
					foreach($moreLikeThisTerms[$fieldName] as $value) {
98
						$do = new DataObject();
99
						$do->Term = $value;
100
						$fieldTerms->push($do);
101
					}
102
103
					$do = new DataObject();
104
					$do->FieldName = $readableFieldName;
105
					$do->Terms = $fieldTerms;
106
					$fieldToTerms->push($do);
107
				}
108
109
				$data['SimilarSearchTerms'] = $fieldToTerms;
110
			} else {
111
				// class does not exist
112
				$data['ErrorMessage'] = "Class $class is either not found or not searchable\n";
113
			}
114
		} catch (\InvalidArgumentException $e) {
115
			$data['ErrorMessage'] = "Class $class is either not found or not searchable\n";
116
		} catch (Elastica\Exception\Connection\HttpException $e) {
117
			$data['ErrorMessage'] = 'Unable to connect to search server';
118
			$data['SearchPerformed'] = false;
119
		}
120
121
122
		$elapsed = $this->calculateTime();
123
		$data['ElapsedTime'] = $elapsed;
124
125
126
		return $this->renderResults($data);
127
	}
128
129
130
131
	/*
132
	Display the search form. If the query parameter exists, search against Elastica
133
	and render results accordingly.
134
	 */
135
	public function index() {
136
		$data = $this->initialiseDataArray();
137
		$es = $this->primeElasticSearcherFromRequest();
138
		$es->setPageLength($this->SearchPage->ResultsPerPage);
139
140
		// Do not show suggestions if this flag is set
141
		$ignoreSuggestions = null !== $this->request->getVar('is');
142
143
144
		// query string
145
		$queryTextParam = $this->request->getVar('q');
146
		$queryText = !empty($queryTextParam) ? $queryTextParam : '';
147
148
		$testMode = !empty($this->request->getVar('TestMode'));
149
150
		// filters for aggregations
151
		$ignore = \Config::inst()->get('Elastica', 'BlackList');
152
		foreach($this->request->getVars() as $key => $value) {
153
			if(!in_array($key, $ignore)) {
154
				$es->addFilter($key, $value);
155
			}
156
		}
157
158
		// filter by class or site tree
159
		if($this->SearchPage->SiteTreeOnly) {
160
			$es->addFilter('IsInSiteTree', true);
161
		} else {
162
			$es->setClasses($this->SearchPage->ClassesToSearch);
163
		}
164
165
		// set the optional aggregation manipulator
166
		// In the event of a manipulator being present, show all the results for search
167
		// Otherwise aggregations are all zero
168
		if($this->SearchHelper) {
169
			$es->setQueryResultManipulator($this->SearchHelper);
170
			$es->showResultsForEmptySearch();
171
		} else {
172
			$es->hideResultsForEmptySearch();
173
		}
174
175
		// get the edited fields to search from the database for this search page
176
		// Convert this into a name => weighting array
177
		$fieldsToSearch = array();
178
		$editedSearchFields = $this->ElasticaSearchableFields()->filter(array(
179
			'Active' => true,
180
			'Searchable' => true
181
		));
182
183
		foreach($editedSearchFields->getIterator() as $searchField) {
184
			$fieldsToSearch[$searchField->Name] = $searchField->Weight;
185
		}
186
187
		$paginated = null;
188
		try {
189
			// Simulate server being down for testing purposes
190
			if(!empty($this->request->getVar('ServerDown'))) {
191
				throw new Elastica\Exception\Connection\HttpException('Unable to reach search server');
192
			}
193
194
			// now actually perform the search using the original query
195
			$paginated = $es->search($queryText, $fieldsToSearch, $testMode);
196
197
			// This is the case of the original query having a better one suggested.  Do a
198
			// second search for the suggested query, throwing away the original
199
			if($es->hasSuggestedQuery() && !$ignoreSuggestions) {
200
				$data['SuggestedQuery'] = $es->getSuggestedQuery();
201
				$data['SuggestedQueryHighlighted'] = $es->getSuggestedQueryHighlighted();
202
				//Link for if the user really wants to try their original query
203
				$sifLink = rtrim($this->Link(), '/') . '?q=' . $queryText . '&is=1';
204
				$data['SearchInsteadForLink'] = $sifLink;
205
				$paginated = $es->search($es->getSuggestedQuery(), $fieldsToSearch);
206
207
			}
208
209
			$elapsed = $this->calculateTime();
210
			$data['ElapsedTime'] = $elapsed;
211
212
			$this->Aggregations = $es->getAggregations();
213
			$this->successfulSearch($data, $paginated);
214
215
		} catch (Elastica\Exception\Connection\HttpException $e) {
216
			$data['ErrorMessage'] = 'Unable to connect to search server';
217
			$data['SearchPerformed'] = false;
218
		}
219
220
		$data['OriginalQuery'] = $queryText;
221
		$data['IgnoreSuggestions'] = $ignoreSuggestions;
222
223
		return $this->renderResults($data);
224
225
	}
226
227
228
	private function successfulSearch(&$data, $paginated) {
229
		$data['SearchResults'] = $paginated;
230
		$data['SearchPerformed'] = true;
231
		$data['NumberOfResults'] = $paginated->getTotalItems();
232
		$data['SearchPageLink'] = $this->SearchPage->Link();
233
	}
234
235
236
	/*
237
	Return true if the query is not empty
238
	 */
239
	public function QueryIsEmpty() {
240
		return empty($this->request->getVar('q'));
241
	}
242
243
244
	/**
245
	 * Process submission of the search form, redirecting to a URL that will render search results
246
	 * @param  array $data form data
247
	 * @param  Form $form form
248
	 */
249
	public function submit($data, $form) {
250
		$queryText = $data['q'];
251
		$url = $this->Link();
252
		$url = rtrim($url, '/');
253
		$link = rtrim($url, '/') . '?q=' . $queryText . '&sfid=' . $data['identifier'];
254
		$this->redirect($link);
255
	}
256
257
258
	/*
259
	Obtain an instance of the form
260
	*/
261
	public function SearchForm() {
262
		$form = new ElasticSearchForm($this, 'SearchForm');
263
		$fields = $form->Fields();
264
		$elasticaSearchPage = Controller::curr()->dataRecord;
265
		$identifierField = new HiddenField('identifier');
266
		$identifierField->setValue($elasticaSearchPage->Identifier);
267
268
		$fields->push($identifierField);
269
		$queryField = $fields->fieldByName('q');
270
271
		 if($this->isParamSet('q') && $this->isParamSet('sfid')) {
272
		 	$sfid = $this->request->getVar('sfid');
273
			if($sfid == $elasticaSearchPage->Identifier) {
274
275
				$queryText = $this->request->getVar('q');
276
				$queryField->setValue($queryText);
277
			}
278
279
		}
280
281
		if($this->action == 'similar') {
282
			$queryField->setDisabled(true);
283
			$actions = $form->Actions();
284
285
			if(!empty($actions)) {
286
				foreach($actions as $field) {
287
					$field->setDisabled(true);
288
				}
289
			}
290
291
		}
292
293
		if($this->AutoCompleteFieldID > 0) {
294
			ElasticaUtil::addAutocompleteToQueryField(
295
				$queryField,
296
				$this->ClassesToSearch,
297
				$this->SiteTreeOnly,
298
				$this->Link(),
299
				$this->AutocompleteFunction()->Slug
300
			);
301
		}
302
		return $form;
303
	}
304
305
306
	/**
307
	 * @param string $paramName
308
	 */
309
	private function isParamSet($paramName) {
310
		return !empty($this->request->getVar($paramName));
311
	}
312
313
314
	/**
315
	 * Set the start page from the request and results per page for a given searcher object
316
	 */
317
	private function primeElasticSearcherFromRequest() {
318
		$elasticSearcher = new ElasticSearcher();
319
		// start, and page length, i.e. pagination
320
		$startParam = $this->request->getVar('start');
321
		$start = isset($startParam) ? $startParam : 0;
322
		$elasticSearcher->setStart($start);
323
		$this->StartTime = microtime(true);
324
		return $elasticSearcher;
325
	}
326
327
328
	/**
329
	 * Set the admin configured similarity parameters
330
	 * @param \SilverStripe\Elastica\ElasticSearcher &$elasticSearcher ElasticaSearcher object
331
	 */
332
	private function setMoreLikeThisParamsFromRequest(&$elasticSearcher) {
333
		$elasticSearcher->setMinTermFreq($this->MinTermFreq);
334
		$elasticSearcher->setMaxTermFreq($this->MaxTermFreq);
335
		$elasticSearcher->setMinDocFreq($this->MinDocFreq);
336
		$elasticSearcher->setMaxDocFreq($this->MaxDocFreq);
337
		$elasticSearcher->setMinWordLength($this->MinWordLength);
338
		$elasticSearcher->setMaxWordLength($this->MaxWordLength);
339
		$elasticSearcher->setMinShouldMatch($this->MinShouldMatch);
340
		$elasticSearcher->setSimilarityStopWords($this->SimilarityStopWords);
341
	}
342
343
344
	private function initialiseDataArray() {
345
		return array(
346
			'Content' => $this->Content,
347
			'Title' => $this->Title,
348
			'SearchPerformed' => false
349
		);
350
	}
351
352
353
354
	private function renderResults($data) {
355
		// allow the optional use of overriding the search result page, e.g. for photos, maps or facets
356
		if($this->hasExtension('PageControllerTemplateOverrideExtension')) {
357
			return $this->useTemplateOverride($data);
358
		} else {
359
			return $data;
360
		}
361
	}
362
363
364
	private function calculateTime() {
365
		$endTime = microtime(true);
366
		$elapsed = round(100 * ($endTime - $this->StartTime)) / 100;
367
		return $elapsed;
368
	}
369
}
370