summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/MediaWiki/Search/Search.php
blob: 5e18e7eb8c461ee590c28cabb0b2bf005f414ec8 (plain)
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
<?php

namespace SMW\MediaWiki\Search;

use Content;
use DatabaseBase;
use RuntimeException;
use SearchEngine;
use SMW\ApplicationFactory;
use SMWQuery;
use SMWQueryResult as QueryResult;
use Title;

/**
 * Search engine that will try to find wiki pages by interpreting the search
 * term as an SMW query.
 *
 * If successful, the pages according to the query will be returned.
 * If not it falls back to the default search engine.
 *
 * @ingroup SMW
 *
 * @license GNU GPL v2+
 * @since   2.1
 *
 * @author  Stephan Gambke
 */
class Search extends SearchEngine {

	private $fallbackSearch = null;

	private $database = null;

	/**
	 * @var array
	 */
	private $errors = [];

	/**
	 * @var QueryBuilder
	 */
	private $queryBuilder;

	/**
	 * @var string
	 */
	private $queryString = '';

	/**
	 * @var InfoLink
	 */
	private $queryLink;

	/**
	 * @see SearchEngine::getValidSorts
	 *
	 * @since 3.0
	 *
	 * @return array
	 */
	public function getValidSorts() {
		return [

			// SemanticMediaWiki supported
			'title', 'recent', 'best',

			// MediaWiki default
			'relevance'
		];
	}

	/**
	 * @param null|SearchEngine $fallbackSearch
	 */
	public function setFallbackSearchEngine( SearchEngine $fallbackSearch = null ) {
		$this->fallbackSearch = $fallbackSearch;
	}

	/**
	 * @param $type
	 */
	private function assertValidFallbackSearchEngineType( $type ) {

		if ( !class_exists( $type ) ) {
			throw new RuntimeException( "$type does not exist." );
		}

		if ( $type === 'SMWSearch' ) {
			throw new RuntimeException( 'SMWSearch is not a valid fallback search engine type.' );
		}

		if ( $type !== 'SearchEngine' && !is_subclass_of( $type, 'SearchEngine' ) ) {
			throw new RuntimeException( "$type is not a valid fallback search engine type." );
		}
	}

	/**
	 * @return SearchEngine
	 */
	public function getFallbackSearchEngine() {

		if ( $this->fallbackSearch === null ) {

			$type = ApplicationFactory::getInstance()->getSettings()->get( 'smwgFallbackSearchType' );

			$dbr = $this->getDB();

			if ( $type === null ) {
				$type = ApplicationFactory::getInstance()->create( 'DefaultSearchEngineTypeForDB', $dbr );
			}

			$this->assertValidFallbackSearchEngineType( $type );

			$this->fallbackSearch = new $type( $dbr );
		}

		return $this->fallbackSearch;
	}

	/**
	 * @since 3.0
	 *
	 * @return []
	 */
	public function getErrors() {
		return $this->errors;
	}

	/**
	 * @since 3.0
	 *
	 * @return string
	 */
	public function getQueryString() {
		return $this->queryString;
	}

	/**
	 * @since 3.0
	 *
	 * @return string
	 */
	public function getQueryLink() {
		return $this->queryLink;
	}

	/**
	 * @param DatabaseBase $connection
	 */
	public function setDB( DatabaseBase $connection ) {
		$this->database = $connection;
		$this->fallbackSearch = null;
	}

	/**
	 * @return \IDatabase
	 */
	public function getDB() {

		if ( $this->database === null ) {
			$this->database = ApplicationFactory::getInstance()->getLoadBalancer()->getConnection( defined( 'DB_REPLICA' ) ? DB_REPLICA : DB_SLAVE );
		}

		return $this->database;
	}

	/**
	 * @param String $term
	 *
	 * @return SMWQuery | null
	 */
	private function getSearchQuery( $term ) {

		if ( $this->queryBuilder === null ) {
			$this->queryBuilder = new QueryBuilder();
		}

		$this->queryString = $this->queryBuilder->getQueryString(
			ApplicationFactory::getInstance()->getStore(),
			$term
		);

		$query = $this->queryBuilder->getQuery(
			$this->queryString
		);

		$this->queryBuilder->addSort( $query );

		$this->queryBuilder->addNamespaceCondition(
			$query,
			$this->searchableNamespaces()
		);

		return $query;
	}

	private function searchFallbackSearchEngine( $term, $fulltext ) {

		$f = $this->getFallbackSearchEngine();
		$f->prefix = $this->prefix;
		$f->namespaces = $this->namespaces;

		$term = $f->transformSearchTerm( $term );
		$term = $f->replacePrefixes( $term );

		return $fulltext ? $f->searchText( $term ) : $f->searchTitle( $term );
	}

	/**
	 * Perform a title-only search query and return a result set.
	 *
	 * This method will try to find wiki pages by interpreting the search term as an SMW query.
	 *
	 * If successful, the pages according to the query will be returned.
	 * If not, it falls back to the default search engine.
	 *
	 * @param string $term Raw search term
	 *
	 * @return SearchResultSet|null
	 */
	public function searchTitle( $term ) {

		if ( $this->getSearchQuery( $term ) !== null ) {
			return null;
		}

		return $this->searchFallbackSearchEngine( $term, false );
	}

	/**
	 * Perform a full text search query and return a result set.
	 * If title searches are not supported or disabled, return null.
	 *
	 * @param string $term Raw search term
	 *
	 * @return SearchResultSet|\Status|null
	 */
	public function searchText( $term ) {

		if ( $this->getSearchQuery( $term ) !== null ) {
			return $this->newSearchResultSet( $term );
		}

		return $this->searchFallbackSearchEngine( $term, true );
	}

	/**
	 * @see SearchEngine::completionSearchBackend
	 *
	 * Perform a completion search.
	 *
	 * @param string $search
	 *
	 * @return SearchSuggestionSet
	 */
	protected function completionSearchBackend( $search ) {

		$searchResultSet = null;

		// Avoid MW's auto formatting of title entities
		if ( $search !== '' ) {
			$search{0} = strtolower( $search{0} );
		}

		$searchEngine = $this->getFallbackSearchEngine();

		if ( !$this->hasPrefixAndMinLenForCompletionSearch( $search, 3 ) ) {
			return $searchEngine->completionSearch( $search );
		}

		if ( $this->getSearchQuery( $search ) !== null ) {
			$searchResultSet = $this->newSearchResultSet( $search, false, false );
		}

		if ( $searchResultSet instanceof SearchResultSet ) {
			return $searchResultSet->newSearchSuggestionSet();
		}

		return $searchEngine->completionSearch( $search );
	}

	private function hasPrefixAndMinLenForCompletionSearch( $term, $minLen ) {

		// Only act on when `in:foo`, `has:SomeProperty`, or `phrase:some text`
		// is actively used as prefix

		if ( strpos( $term, 'in:' ) !== false && mb_strlen( $term ) >= ( 3 + $minLen ) ) {
			return true;
		}

		if ( strpos( $term, 'has:' ) !== false && mb_strlen( $term ) >= ( 4 + $minLen ) ) {
			return true;
		}

		if ( strpos( $term, 'phrase:' ) !== false && mb_strlen( $term ) >= ( 7 + $minLen ) ) {
			return true;
		}

		return false;
	}

	private function newSearchResultSet( $term, $count = true, $highlight = true ) {

		$query = $this->getSearchQuery( $term );

		if ( $query === null ) {
			return null;
		}

		$query->setOffset( $this->offset );
		$query->setLimit( $this->limit, false );
		$this->queryString = $query->getQueryString();

		$store = ApplicationFactory::getInstance()->getStore();
		$query->clearErrors();
		$query->setOption( 'highlight.fragment', $highlight );

		$result = $store->getQueryResult( $query );
		$this->errors = $query->getErrors();
		$this->queryLink = $result->getQueryLink();
		$this->queryLink->setParameter( $this->offset, 'offset' );
		$this->queryLink->setParameter( $this->limit, 'limit' );

		if ( $count ) {
			$query->querymode = SMWQuery::MODE_COUNT;
			$query->setOffset( 0 );

			$queryResult = $store->getQueryResult( $query );
			$count = $queryResult instanceof QueryResult ? $queryResult->getCountValue() : $queryResult;
		} else {
			$count = 0;
		}

		return new SearchResultSet( $result, $count );
	}

	/**
	 * @param string $feature
	 *
	 * @return bool
	 */
	public function supports( $feature ) {
		return $this->getFallbackSearchEngine()->supports( $feature );
	}

	/**
	 * May performs database-specific conversions on text to be used for
	 * searching or updating search index.
	 *
	 * @param string $string String to process
	 *
	 * @return string
	 */
	public function normalizeText( $string ) {
		return $this->getFallbackSearchEngine()->normalizeText( $string );
	}

	public function getTextFromContent( Title $t, Content $c = null ) {
		return $this->getFallbackSearchEngine()->getTextFromContent( $t, $c );
	}

	public function textAlreadyUpdatedForIndex() {
		return $this->getFallbackSearchEngine()->textAlreadyUpdatedForIndex();
	}

	/**
	 * Create or update the search index record for the given page.
	 * Title and text should be pre-processed.
	 *
	 * @param int    $id
	 * @param string $title
	 * @param string $text
	 */
	public function update( $id, $title, $text ) {
		$this->getFallbackSearchEngine()->update( $id, $title, $text );
	}

	/**
	 * Update a search index record's title only.
	 * Title should be pre-processed.
	 *
	 * @param int    $id
	 * @param string $title
	 */
	public function updateTitle( $id, $title ) {
		$this->getFallbackSearchEngine()->updateTitle( $id, $title );
	}

	/**
	 * Delete an indexed page
	 * Title should be pre-processed.
	 *
	 * @param int    $id    Page id that was deleted
	 * @param string $title Title of page that was deleted
	 */
	public function delete( $id, $title ) {
		$this->getFallbackSearchEngine()->delete( $id, $title );
	}

	public function setFeatureData( $feature, $data ) {
		parent::setFeatureData( $feature, $data );
		$this->getFallbackSearchEngine()->setFeatureData( $feature, $data );
	}

	/**
	 * @param String $feature
	 *
	 * @return array|null
	 */
	public function getFeatureData( $feature ) {

		if ( array_key_exists( $feature, $this->features ) ) {
			return $this->features[$feature];
		}

		return null;
	}

	/**
	 * SMW queries do not have prefixes. Returns query as is.
	 *
	 * @param string $query
	 *
	 * @return string
	 */
	public function replacePrefixes( $query ) {
		return $query;
	}

	/**
	 * No Transformation needed. Returns term as is.
	 * @param $term
	 * @return mixed
	 */
	public function transformSearchTerm( $term ) {
		return $term;
	}

	/**
	 * @return int
	 */
	public function getLimit() {
		return $this->limit;
	}

	/**
	 * @return int
	 */
	public function getOffset() {
		return $this->offset;
	}

	/**
	 * @return boolean
	 */
	public function getShowSuggestion() {
		return $this->showSuggestion;
	}

	public function setLimitOffset( $limit, $offset = 0 ) {
		parent::setLimitOffset( $limit, $offset );
		$this->getFallbackSearchEngine()->setLimitOffset( $limit, $offset );
	}

	public function setNamespaces( $namespaces ) {
		parent::setNamespaces( $namespaces );
		$this->getFallbackSearchEngine()->setNamespaces( $namespaces );
	}

	public function setShowSuggestion( $showSuggestion ) {
		parent::setShowSuggestion( $showSuggestion );
		$this->getFallbackSearchEngine()->setShowSuggestion( $showSuggestion );
	}
}