Completed
Push — dev2 ( 1cdcda...1d8072 )
by Gordon
03:03
created

ElasticSearchPage_Controller::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

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