3d2057c528611e159ac79ec945deca0d448f9567
[lhc/web/wiklou.git] / includes / search / SearchEngine.php
1 <?php
2 /**
3 * Basic search engine
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Search
22 */
23
24 /**
25 * @defgroup Search Search
26 */
27
28 use MediaWiki\MediaWikiServices;
29
30 /**
31 * Contain a class for special pages
32 * @ingroup Search
33 */
34 abstract class SearchEngine {
35 /** @var string */
36 public $prefix = '';
37
38 /** @var int[]|null */
39 public $namespaces = [ NS_MAIN ];
40
41 /** @var int */
42 protected $limit = 10;
43
44 /** @var int */
45 protected $offset = 0;
46
47 /** @var array|string */
48 protected $searchTerms = [];
49
50 /** @var bool */
51 protected $showSuggestion = true;
52 private $sort = 'relevance';
53
54 /** @var array Feature values */
55 protected $features = [];
56
57 /**
58 * Perform a full text search query and return a result set.
59 * If full text searches are not supported or disabled, return null.
60 * STUB
61 *
62 * @param string $term Raw search term
63 * @return SearchResultSet|Status|null
64 */
65 function searchText( $term ) {
66 return null;
67 }
68
69 /**
70 * Perform a title-only search query and return a result set.
71 * If title searches are not supported or disabled, return null.
72 * STUB
73 *
74 * @param string $term Raw search term
75 * @return SearchResultSet|null
76 */
77 function searchTitle( $term ) {
78 return null;
79 }
80
81 /**
82 * @since 1.18
83 * @param string $feature
84 * @return bool
85 */
86 public function supports( $feature ) {
87 switch ( $feature ) {
88 case 'search-update':
89 return true;
90 case 'title-suffix-filter':
91 default:
92 return false;
93 }
94 }
95
96 /**
97 * Way to pass custom data for engines
98 * @since 1.18
99 * @param string $feature
100 * @param mixed $data
101 * @return bool
102 */
103 public function setFeatureData( $feature, $data ) {
104 $this->features[$feature] = $data;
105 }
106
107 /**
108 * When overridden in derived class, performs database-specific conversions
109 * on text to be used for searching or updating search index.
110 * Default implementation does nothing (simply returns $string).
111 *
112 * @param string $string String to process
113 * @return string
114 */
115 public function normalizeText( $string ) {
116 global $wgContLang;
117
118 // Some languages such as Chinese require word segmentation
119 return $wgContLang->segmentByWord( $string );
120 }
121
122 /**
123 * Transform search term in cases when parts of the query came as different
124 * GET params (when supported), e.g. for prefix queries:
125 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
126 * @param string $term
127 * @return string
128 */
129 public function transformSearchTerm( $term ) {
130 return $term;
131 }
132
133 /**
134 * Get service class to finding near matches.
135 * @param Config $config Configuration to use for the matcher.
136 * @return SearchNearMatcher
137 */
138 public function getNearMatcher( Config $config ) {
139 return new SearchNearMatcher( $config );
140 }
141
142 /**
143 * Get near matcher for default SearchEngine.
144 * @return SearchNearMatcher
145 */
146 protected static function defaultNearMatcher() {
147 $config = MediaWikiServices::getInstance()->getMainConfig();
148 return MediaWikiServices::getInstance()->newSearchEngine()->getNearMatcher( $config );
149 }
150
151 /**
152 * If an exact title match can be found, or a very slightly close match,
153 * return the title. If no match, returns NULL.
154 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
155 * @param string $searchterm
156 * @return Title
157 */
158 public static function getNearMatch( $searchterm ) {
159 return static::defaultNearMatcher()->getNearMatch( $searchterm );
160 }
161
162 /**
163 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
164 * SearchResultSet.
165 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
166 * @param string $searchterm
167 * @return SearchResultSet
168 */
169 public static function getNearMatchResultSet( $searchterm ) {
170 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
171 }
172
173 /**
174 * Get chars legal for search.
175 * NOTE: usage as static is deprecated and preserved only as BC measure
176 * @return string
177 */
178 public static function legalSearchChars() {
179 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
180 }
181
182 /**
183 * Set the maximum number of results to return
184 * and how many to skip before returning the first.
185 *
186 * @param int $limit
187 * @param int $offset
188 */
189 function setLimitOffset( $limit, $offset = 0 ) {
190 $this->limit = intval( $limit );
191 $this->offset = intval( $offset );
192 }
193
194 /**
195 * Set which namespaces the search should include.
196 * Give an array of namespace index numbers.
197 *
198 * @param int[]|null $namespaces
199 */
200 function setNamespaces( $namespaces ) {
201 if ( $namespaces ) {
202 // Filter namespaces to only keep valid ones
203 $validNs = $this->searchableNamespaces();
204 $namespaces = array_filter( $namespaces, function( $ns ) use( $validNs ) {
205 return $ns < 0 || isset( $validNs[$ns] );
206 } );
207 } else {
208 $namespaces = [];
209 }
210 $this->namespaces = $namespaces;
211 }
212
213 /**
214 * Set whether the searcher should try to build a suggestion. Note: some searchers
215 * don't support building a suggestion in the first place and others don't respect
216 * this flag.
217 *
218 * @param bool $showSuggestion Should the searcher try to build suggestions
219 */
220 function setShowSuggestion( $showSuggestion ) {
221 $this->showSuggestion = $showSuggestion;
222 }
223
224 /**
225 * Get the valid sort directions. All search engines support 'relevance' but others
226 * might support more. The default in all implementations should be 'relevance.'
227 *
228 * @since 1.25
229 * @return array(string) the valid sort directions for setSort
230 */
231 public function getValidSorts() {
232 return [ 'relevance' ];
233 }
234
235 /**
236 * Set the sort direction of the search results. Must be one returned by
237 * SearchEngine::getValidSorts()
238 *
239 * @since 1.25
240 * @throws InvalidArgumentException
241 * @param string $sort sort direction for query result
242 */
243 public function setSort( $sort ) {
244 if ( !in_array( $sort, $this->getValidSorts() ) ) {
245 throw new InvalidArgumentException( "Invalid sort: $sort. " .
246 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
247 }
248 $this->sort = $sort;
249 }
250
251 /**
252 * Get the sort direction of the search results
253 *
254 * @since 1.25
255 * @return string
256 */
257 public function getSort() {
258 return $this->sort;
259 }
260
261 /**
262 * Parse some common prefixes: all (search everything)
263 * or namespace names
264 *
265 * @param string $query
266 * @return string
267 */
268 function replacePrefixes( $query ) {
269 global $wgContLang;
270
271 $parsed = $query;
272 if ( strpos( $query, ':' ) === false ) { // nothing to do
273 return $parsed;
274 }
275
276 $allkeyword = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
277 if ( strncmp( $query, $allkeyword, strlen( $allkeyword ) ) == 0 ) {
278 $this->namespaces = null;
279 $parsed = substr( $query, strlen( $allkeyword ) );
280 } elseif ( strpos( $query, ':' ) !== false ) {
281 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
282 $index = $wgContLang->getNsIndex( $prefix );
283 if ( $index !== false ) {
284 $this->namespaces = [ $index ];
285 $parsed = substr( $query, strlen( $prefix ) + 1 );
286 }
287 }
288 if ( trim( $parsed ) == '' ) {
289 $parsed = $query; // prefix was the whole query
290 }
291
292 return $parsed;
293 }
294
295 /**
296 * Find snippet highlight settings for all users
297 * @return array Contextlines, contextchars
298 */
299 public static function userHighlightPrefs() {
300 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
301 $contextchars = 75; // same as above.... :P
302 return [ $contextlines, $contextchars ];
303 }
304
305 /**
306 * Create or update the search index record for the given page.
307 * Title and text should be pre-processed.
308 * STUB
309 *
310 * @param int $id
311 * @param string $title
312 * @param string $text
313 */
314 function update( $id, $title, $text ) {
315 // no-op
316 }
317
318 /**
319 * Update a search index record's title only.
320 * Title should be pre-processed.
321 * STUB
322 *
323 * @param int $id
324 * @param string $title
325 */
326 function updateTitle( $id, $title ) {
327 // no-op
328 }
329
330 /**
331 * Delete an indexed page
332 * Title should be pre-processed.
333 * STUB
334 *
335 * @param int $id Page id that was deleted
336 * @param string $title Title of page that was deleted
337 */
338 function delete( $id, $title ) {
339 // no-op
340 }
341
342 /**
343 * Get OpenSearch suggestion template
344 *
345 * @deprecated since 1.25
346 * @return string
347 */
348 public static function getOpenSearchTemplate() {
349 wfDeprecated( __METHOD__, '1.25' );
350 return ApiOpenSearch::getOpenSearchTemplate( 'application/x-suggestions+json' );
351 }
352
353 /**
354 * Get the raw text for updating the index from a content object
355 * Nicer search backends could possibly do something cooler than
356 * just returning raw text
357 *
358 * @todo This isn't ideal, we'd really like to have content-specific handling here
359 * @param Title $t Title we're indexing
360 * @param Content $c Content of the page to index
361 * @return string
362 */
363 public function getTextFromContent( Title $t, Content $c = null ) {
364 return $c ? $c->getTextForSearchIndex() : '';
365 }
366
367 /**
368 * If an implementation of SearchEngine handles all of its own text processing
369 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
370 * rather silly handling, it should return true here instead.
371 *
372 * @return bool
373 */
374 public function textAlreadyUpdatedForIndex() {
375 return false;
376 }
377
378 /**
379 * Makes search simple string if it was namespaced.
380 * Sets namespaces of the search to namespaces extracted from string.
381 * @param string $search
382 * @return $string Simplified search string
383 */
384 protected function normalizeNamespaces( $search ) {
385 // Find a Title which is not an interwiki and is in NS_MAIN
386 $title = Title::newFromText( $search );
387 $ns = $this->namespaces;
388 if ( $title && !$title->isExternal() ) {
389 $ns = [ $title->getNamespace() ];
390 $search = $title->getText();
391 if ( $ns[0] == NS_MAIN ) {
392 $ns = $this->namespaces; // no explicit prefix, use default namespaces
393 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
394 }
395 } else {
396 $title = Title::newFromText( $search . 'Dummy' );
397 if ( $title && $title->getText() == 'Dummy'
398 && $title->getNamespace() != NS_MAIN
399 && !$title->isExternal() )
400 {
401 $ns = [ $title->getNamespace() ];
402 $search = '';
403 } else {
404 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
405 }
406 }
407
408 $ns = array_map( function( $space ) {
409 return $space == NS_MEDIA ? NS_FILE : $space;
410 }, $ns );
411
412 $this->setNamespaces( $ns );
413 return $search;
414 }
415
416 /**
417 * Perform a completion search.
418 * Does not resolve namespaces and does not check variants.
419 * Search engine implementations may want to override this function.
420 * @param string $search
421 * @return SearchSuggestionSet
422 */
423 protected function completionSearchBackend( $search ) {
424 $results = [];
425
426 $search = trim( $search );
427
428 if ( !in_array( NS_SPECIAL, $this->namespaces ) && // We do not run hook on Special: search
429 !Hooks::run( 'PrefixSearchBackend',
430 [ $this->namespaces, $search, $this->limit, &$results, $this->offset ]
431 ) ) {
432 // False means hook worked.
433 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
434
435 return SearchSuggestionSet::fromStrings( $results );
436 } else {
437 // Hook did not do the job, use default simple search
438 $results = $this->simplePrefixSearch( $search );
439 return SearchSuggestionSet::fromTitles( $results );
440 }
441 }
442
443 /**
444 * Perform a completion search.
445 * @param string $search
446 * @return SearchSuggestionSet
447 */
448 public function completionSearch( $search ) {
449 if ( trim( $search ) === '' ) {
450 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
451 }
452 $search = $this->normalizeNamespaces( $search );
453 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
454 }
455
456 /**
457 * Perform a completion search with variants.
458 * @param string $search
459 * @return SearchSuggestionSet
460 */
461 public function completionSearchWithVariants( $search ) {
462 if ( trim( $search ) === '' ) {
463 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
464 }
465 $search = $this->normalizeNamespaces( $search );
466
467 $results = $this->completionSearchBackend( $search );
468 $fallbackLimit = $this->limit - $results->getSize();
469 if ( $fallbackLimit > 0 ) {
470 global $wgContLang;
471
472 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
473 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
474
475 foreach ( $fallbackSearches as $fbs ) {
476 $this->setLimitOffset( $fallbackLimit );
477 $fallbackSearchResult = $this->completionSearch( $fbs );
478 $results->appendAll( $fallbackSearchResult );
479 $fallbackLimit -= count( $fallbackSearchResult );
480 if ( $fallbackLimit <= 0 ) {
481 break;
482 }
483 }
484 }
485 return $this->processCompletionResults( $search, $results );
486 }
487
488 /**
489 * Extract titles from completion results
490 * @param SearchSuggestionSet $completionResults
491 * @return Title[]
492 */
493 public function extractTitles( SearchSuggestionSet $completionResults ) {
494 return $completionResults->map( function( SearchSuggestion $sugg ) {
495 return $sugg->getSuggestedTitle();
496 } );
497 }
498
499 /**
500 * Process completion search results.
501 * Resolves the titles and rescores.
502 * @param SearchSuggestionSet $suggestions
503 * @return SearchSuggestionSet
504 */
505 protected function processCompletionResults( $search, SearchSuggestionSet $suggestions ) {
506 $search = trim( $search );
507 // preload the titles with LinkBatch
508 $titles = $suggestions->map( function( SearchSuggestion $sugg ) {
509 return $sugg->getSuggestedTitle();
510 } );
511 $lb = new LinkBatch( $titles );
512 $lb->setCaller( __METHOD__ );
513 $lb->execute();
514
515 $results = $suggestions->map( function( SearchSuggestion $sugg ) {
516 return $sugg->getSuggestedTitle()->getPrefixedText();
517 } );
518
519 // Rescore results with an exact title match
520 // NOTE: in some cases like cross-namespace redirects
521 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
522 // backends like Cirrus will return no results. We should still
523 // try an exact title match to workaround this limitation
524 $rescorer = new SearchExactMatchRescorer();
525 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
526
527 if ( count( $rescoredResults ) > 0 ) {
528 $found = array_search( $rescoredResults[0], $results );
529 if ( $found === false ) {
530 // If the first result is not in the previous array it
531 // means that we found a new exact match
532 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
533 $suggestions->prepend( $exactMatch );
534 $suggestions->shrink( $this->limit );
535 } else {
536 // if the first result is not the same we need to rescore
537 if ( $found > 0 ) {
538 $suggestions->rescore( $found );
539 }
540 }
541 }
542
543 return $suggestions;
544 }
545
546 /**
547 * Simple prefix search for subpages.
548 * @param string $search
549 * @return Title[]
550 */
551 public function defaultPrefixSearch( $search ) {
552 if ( trim( $search ) === '' ) {
553 return [];
554 }
555
556 $search = $this->normalizeNamespaces( $search );
557 return $this->simplePrefixSearch( $search );
558 }
559
560 /**
561 * Call out to simple search backend.
562 * Defaults to TitlePrefixSearch.
563 * @param string $search
564 * @return Title[]
565 */
566 protected function simplePrefixSearch( $search ) {
567 // Use default database prefix search
568 $backend = new TitlePrefixSearch;
569 return $backend->defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
570 }
571
572 /**
573 * Make a list of searchable namespaces and their canonical names.
574 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
575 * @return array
576 */
577 public static function searchableNamespaces() {
578 return MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
579 }
580
581 /**
582 * Extract default namespaces to search from the given user's
583 * settings, returning a list of index numbers.
584 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
585 * @param user $user
586 * @return array
587 */
588 public static function userNamespaces( $user ) {
589 return MediaWikiServices::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
590 }
591
592 /**
593 * An array of namespaces indexes to be searched by default
594 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
595 * @return array
596 */
597 public static function defaultNamespaces() {
598 return MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
599 }
600
601 /**
602 * Get a list of namespace names useful for showing in tooltips
603 * and preferences
604 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
605 * @param array $namespaces
606 * @return array
607 */
608 public static function namespacesAsText( $namespaces ) {
609 return MediaWikiServices::getInstance()->getSearchEngineConfig()->namespacesAsText();
610 }
611
612 /**
613 * Load up the appropriate search engine class for the currently
614 * active database backend, and return a configured instance.
615 * @deprecated since 1.27; Use SearchEngineFactory::create
616 * @param string $type Type of search backend, if not the default
617 * @return SearchEngine
618 */
619 public static function create( $type = null ) {
620 return MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $type );
621 }
622
623 /**
624 * Return the search engines we support. If only $wgSearchType
625 * is set, it'll be an array of just that one item.
626 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
627 * @return array
628 */
629 public static function getSearchTypes() {
630 return MediaWikiServices::getInstance()->getSearchEngineConfig()->getSearchTypes();
631 }
632
633 }
634
635 /**
636 * Dummy class to be used when non-supported Database engine is present.
637 * @todo FIXME: Dummy class should probably try something at least mildly useful,
638 * such as a LIKE search through titles.
639 * @ingroup Search
640 */
641 class SearchEngineDummy extends SearchEngine {
642 // no-op
643 }