Fix 'Tags' padding to keep it farther from the edge and document the source of the...
[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 /** @const string profile type for completionSearch */
58 const COMPLETION_PROFILE_TYPE = 'completionSearchProfile';
59
60 /** @const string profile type for query independent ranking features */
61 const FT_QUERY_INDEP_PROFILE_TYPE = 'fulltextQueryIndepProfile';
62
63 /** @const int flag for legalSearchChars: includes all chars allowed in a search query */
64 const CHARS_ALL = 1;
65
66 /** @const int flag for legalSearchChars: includes all chars allowed in a search term */
67 const CHARS_NO_SYNTAX = 2;
68
69 /**
70 * Perform a full text search query and return a result set.
71 * If full text searches are not supported or disabled, return null.
72 *
73 * As of 1.32 overriding this function is deprecated. It will
74 * be converted to final in 1.34. Override self::doSearchText().
75 *
76 * @param string $term Raw search term
77 * @return SearchResultSet|Status|null
78 */
79 public function searchText( $term ) {
80 return $this->doSearchText( $term );
81 }
82
83 /**
84 * Perform a full text search query and return a result set.
85 *
86 * @param string $term Raw search term
87 * @return SearchResultSet|Status|null
88 * @since 1.32
89 */
90 protected function doSearchText( $term ) {
91 return null;
92 }
93
94 /**
95 * Perform a title search in the article archive.
96 * NOTE: these results still should be filtered by
97 * matching against PageArchive, permissions checks etc
98 * The results returned by this methods are only sugegstions and
99 * may not end up being shown to the user.
100 *
101 * As of 1.32 overriding this function is deprecated. It will
102 * be converted to final in 1.34. Override self::doSearchArchiveTitle().
103 *
104 * @param string $term Raw search term
105 * @return Status<Title[]>
106 * @since 1.29
107 */
108 public function searchArchiveTitle( $term ) {
109 return $this->doSearchArchiveTitle( $term );
110 }
111
112 /**
113 * Perform a title search in the article archive.
114 *
115 * @param string $term Raw search term
116 * @return Status<Title[]>
117 * @since 1.32
118 */
119 protected function doSearchArchiveTitle( $term ) {
120 return Status::newGood( [] );
121 }
122
123 /**
124 * Perform a title-only search query and return a result set.
125 * If title searches are not supported or disabled, return null.
126 * STUB
127 *
128 * As of 1.32 overriding this function is deprecated. It will
129 * be converted to final in 1.34. Override self::doSearchTitle().
130 *
131 * @param string $term Raw search term
132 * @return SearchResultSet|null
133 */
134 public function searchTitle( $term ) {
135 return $this->doSearchTitle( $term );
136 }
137
138 /**
139 * Perform a title-only search query and return a result set.
140 *
141 * @param string $term Raw search term
142 * @return SearchResultSet|null
143 * @since 1.32
144 */
145 protected function doSearchTitle( $term ) {
146 return null;
147 }
148
149 /**
150 * @since 1.18
151 * @param string $feature
152 * @return bool
153 */
154 public function supports( $feature ) {
155 switch ( $feature ) {
156 case 'search-update':
157 return true;
158 case 'title-suffix-filter':
159 default:
160 return false;
161 }
162 }
163
164 /**
165 * Way to pass custom data for engines
166 * @since 1.18
167 * @param string $feature
168 * @param mixed $data
169 */
170 public function setFeatureData( $feature, $data ) {
171 $this->features[$feature] = $data;
172 }
173
174 /**
175 * Way to retrieve custom data set by setFeatureData
176 * or by the engine itself.
177 * @since 1.29
178 * @param string $feature feature name
179 * @return mixed the feature value or null if unset
180 */
181 public function getFeatureData( $feature ) {
182 if ( isset( $this->features[$feature] ) ) {
183 return $this->features[$feature];
184 }
185 return null;
186 }
187
188 /**
189 * When overridden in derived class, performs database-specific conversions
190 * on text to be used for searching or updating search index.
191 * Default implementation does nothing (simply returns $string).
192 *
193 * @param string $string String to process
194 * @return string
195 */
196 public function normalizeText( $string ) {
197 global $wgContLang;
198
199 // Some languages such as Chinese require word segmentation
200 return $wgContLang->segmentByWord( $string );
201 }
202
203 /**
204 * Transform search term in cases when parts of the query came as different
205 * GET params (when supported), e.g. for prefix queries:
206 * search=test&prefix=Main_Page/Archive -> test prefix:Main Page/Archive
207 * @param string $term
208 * @return string
209 */
210 public function transformSearchTerm( $term ) {
211 return $term;
212 }
213
214 /**
215 * Get service class to finding near matches.
216 * @param Config $config Configuration to use for the matcher.
217 * @return SearchNearMatcher
218 */
219 public function getNearMatcher( Config $config ) {
220 global $wgContLang;
221 return new SearchNearMatcher( $config, $wgContLang );
222 }
223
224 /**
225 * Get near matcher for default SearchEngine.
226 * @return SearchNearMatcher
227 */
228 protected static function defaultNearMatcher() {
229 $config = MediaWikiServices::getInstance()->getMainConfig();
230 return MediaWikiServices::getInstance()->newSearchEngine()->getNearMatcher( $config );
231 }
232
233 /**
234 * If an exact title match can be found, or a very slightly close match,
235 * return the title. If no match, returns NULL.
236 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
237 * @param string $searchterm
238 * @return Title
239 */
240 public static function getNearMatch( $searchterm ) {
241 return static::defaultNearMatcher()->getNearMatch( $searchterm );
242 }
243
244 /**
245 * Do a near match (see SearchEngine::getNearMatch) and wrap it into a
246 * SearchResultSet.
247 * @deprecated since 1.27; Use SearchEngine::getNearMatcher()
248 * @param string $searchterm
249 * @return SearchResultSet
250 */
251 public static function getNearMatchResultSet( $searchterm ) {
252 return static::defaultNearMatcher()->getNearMatchResultSet( $searchterm );
253 }
254
255 /**
256 * Get chars legal for search
257 * NOTE: usage as static is deprecated and preserved only as BC measure
258 * @param int $type type of search chars (see self::CHARS_ALL
259 * and self::CHARS_NO_SYNTAX). Defaults to CHARS_ALL
260 * @return string
261 */
262 public static function legalSearchChars( $type = self::CHARS_ALL ) {
263 return "A-Za-z_'.0-9\\x80-\\xFF\\-";
264 }
265
266 /**
267 * Set the maximum number of results to return
268 * and how many to skip before returning the first.
269 *
270 * @param int $limit
271 * @param int $offset
272 */
273 function setLimitOffset( $limit, $offset = 0 ) {
274 $this->limit = intval( $limit );
275 $this->offset = intval( $offset );
276 }
277
278 /**
279 * Set which namespaces the search should include.
280 * Give an array of namespace index numbers.
281 *
282 * @param int[]|null $namespaces
283 */
284 function setNamespaces( $namespaces ) {
285 if ( $namespaces ) {
286 // Filter namespaces to only keep valid ones
287 $validNs = $this->searchableNamespaces();
288 $namespaces = array_filter( $namespaces, function ( $ns ) use( $validNs ) {
289 return $ns < 0 || isset( $validNs[$ns] );
290 } );
291 } else {
292 $namespaces = [];
293 }
294 $this->namespaces = $namespaces;
295 }
296
297 /**
298 * Set whether the searcher should try to build a suggestion. Note: some searchers
299 * don't support building a suggestion in the first place and others don't respect
300 * this flag.
301 *
302 * @param bool $showSuggestion Should the searcher try to build suggestions
303 */
304 function setShowSuggestion( $showSuggestion ) {
305 $this->showSuggestion = $showSuggestion;
306 }
307
308 /**
309 * Get the valid sort directions. All search engines support 'relevance' but others
310 * might support more. The default in all implementations should be 'relevance.'
311 *
312 * @since 1.25
313 * @return string[] the valid sort directions for setSort
314 */
315 public function getValidSorts() {
316 return [ 'relevance' ];
317 }
318
319 /**
320 * Set the sort direction of the search results. Must be one returned by
321 * SearchEngine::getValidSorts()
322 *
323 * @since 1.25
324 * @throws InvalidArgumentException
325 * @param string $sort sort direction for query result
326 */
327 public function setSort( $sort ) {
328 if ( !in_array( $sort, $this->getValidSorts() ) ) {
329 throw new InvalidArgumentException( "Invalid sort: $sort. " .
330 "Must be one of: " . implode( ', ', $this->getValidSorts() ) );
331 }
332 $this->sort = $sort;
333 }
334
335 /**
336 * Get the sort direction of the search results
337 *
338 * @since 1.25
339 * @return string
340 */
341 public function getSort() {
342 return $this->sort;
343 }
344
345 /**
346 * Parse some common prefixes: all (search everything)
347 * or namespace names and set the list of namespaces
348 * of this class accordingly.
349 *
350 * @param string $query
351 * @return string
352 */
353 function replacePrefixes( $query ) {
354 $queryAndNs = self::parseNamespacePrefixes( $query );
355 if ( $queryAndNs === false ) {
356 return $query;
357 }
358 $this->namespaces = $queryAndNs[1];
359 return $queryAndNs[0];
360 }
361
362 /**
363 * Parse some common prefixes: all (search everything)
364 * or namespace names
365 *
366 * @param string $query
367 * @return false|array false if no namespace was extracted, an array
368 * with the parsed query at index 0 and an array of namespaces at index
369 * 1 (or null for all namespaces).
370 */
371 public static function parseNamespacePrefixes( $query ) {
372 global $wgContLang;
373
374 $parsed = $query;
375 if ( strpos( $query, ':' ) === false ) { // nothing to do
376 return false;
377 }
378 $extractedNamespace = null;
379 $allkeywords = [];
380
381 $allkeywords[] = wfMessage( 'searchall' )->inContentLanguage()->text() . ":";
382 // force all: so that we have a common syntax for all the wikis
383 if ( !in_array( 'all:', $allkeywords ) ) {
384 $allkeywords[] = 'all:';
385 }
386
387 $allQuery = false;
388 foreach ( $allkeywords as $kw ) {
389 if ( strncmp( $query, $kw, strlen( $kw ) ) == 0 ) {
390 $extractedNamespace = null;
391 $parsed = substr( $query, strlen( $kw ) );
392 $allQuery = true;
393 break;
394 }
395 }
396
397 if ( !$allQuery && strpos( $query, ':' ) !== false ) {
398 // TODO: should we unify with PrefixSearch::extractNamespace ?
399 $prefix = str_replace( ' ', '_', substr( $query, 0, strpos( $query, ':' ) ) );
400 $index = $wgContLang->getNsIndex( $prefix );
401 if ( $index !== false ) {
402 $extractedNamespace = [ $index ];
403 $parsed = substr( $query, strlen( $prefix ) + 1 );
404 } else {
405 return false;
406 }
407 }
408
409 if ( trim( $parsed ) == '' ) {
410 $parsed = $query; // prefix was the whole query
411 }
412
413 return [ $parsed, $extractedNamespace ];
414 }
415
416 /**
417 * Find snippet highlight settings for all users
418 * @return array Contextlines, contextchars
419 */
420 public static function userHighlightPrefs() {
421 $contextlines = 2; // Hardcode this. Old defaults sucked. :)
422 $contextchars = 75; // same as above.... :P
423 return [ $contextlines, $contextchars ];
424 }
425
426 /**
427 * Create or update the search index record for the given page.
428 * Title and text should be pre-processed.
429 * STUB
430 *
431 * @param int $id
432 * @param string $title
433 * @param string $text
434 */
435 function update( $id, $title, $text ) {
436 // no-op
437 }
438
439 /**
440 * Update a search index record's title only.
441 * Title should be pre-processed.
442 * STUB
443 *
444 * @param int $id
445 * @param string $title
446 */
447 function updateTitle( $id, $title ) {
448 // no-op
449 }
450
451 /**
452 * Delete an indexed page
453 * Title should be pre-processed.
454 * STUB
455 *
456 * @param int $id Page id that was deleted
457 * @param string $title Title of page that was deleted
458 */
459 function delete( $id, $title ) {
460 // no-op
461 }
462
463 /**
464 * Get the raw text for updating the index from a content object
465 * Nicer search backends could possibly do something cooler than
466 * just returning raw text
467 *
468 * @todo This isn't ideal, we'd really like to have content-specific handling here
469 * @param Title $t Title we're indexing
470 * @param Content $c Content of the page to index
471 * @return string
472 */
473 public function getTextFromContent( Title $t, Content $c = null ) {
474 return $c ? $c->getTextForSearchIndex() : '';
475 }
476
477 /**
478 * If an implementation of SearchEngine handles all of its own text processing
479 * in getTextFromContent() and doesn't require SearchUpdate::updateText()'s
480 * rather silly handling, it should return true here instead.
481 *
482 * @return bool
483 */
484 public function textAlreadyUpdatedForIndex() {
485 return false;
486 }
487
488 /**
489 * Makes search simple string if it was namespaced.
490 * Sets namespaces of the search to namespaces extracted from string.
491 * @param string $search
492 * @return string Simplified search string
493 */
494 protected function normalizeNamespaces( $search ) {
495 // Find a Title which is not an interwiki and is in NS_MAIN
496 $title = Title::newFromText( $search );
497 $ns = $this->namespaces;
498 if ( $title && !$title->isExternal() ) {
499 $ns = [ $title->getNamespace() ];
500 $search = $title->getText();
501 if ( $ns[0] == NS_MAIN ) {
502 $ns = $this->namespaces; // no explicit prefix, use default namespaces
503 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
504 }
505 } else {
506 $title = Title::newFromText( $search . 'Dummy' );
507 if ( $title && $title->getText() == 'Dummy'
508 && $title->getNamespace() != NS_MAIN
509 && !$title->isExternal()
510 ) {
511 $ns = [ $title->getNamespace() ];
512 $search = '';
513 } else {
514 Hooks::run( 'PrefixSearchExtractNamespace', [ &$ns, &$search ] );
515 }
516 }
517
518 $ns = array_map( function ( $space ) {
519 return $space == NS_MEDIA ? NS_FILE : $space;
520 }, $ns );
521
522 $this->setNamespaces( $ns );
523 return $search;
524 }
525
526 /**
527 * Perform a completion search.
528 * Does not resolve namespaces and does not check variants.
529 * Search engine implementations may want to override this function.
530 * @param string $search
531 * @return SearchSuggestionSet
532 */
533 protected function completionSearchBackend( $search ) {
534 $results = [];
535
536 $search = trim( $search );
537
538 if ( !in_array( NS_SPECIAL, $this->namespaces ) && // We do not run hook on Special: search
539 !Hooks::run( 'PrefixSearchBackend',
540 [ $this->namespaces, $search, $this->limit, &$results, $this->offset ]
541 ) ) {
542 // False means hook worked.
543 // FIXME: Yes, the API is weird. That's why it is going to be deprecated.
544
545 return SearchSuggestionSet::fromStrings( $results );
546 } else {
547 // Hook did not do the job, use default simple search
548 $results = $this->simplePrefixSearch( $search );
549 return SearchSuggestionSet::fromTitles( $results );
550 }
551 }
552
553 /**
554 * Perform a completion search.
555 * @param string $search
556 * @return SearchSuggestionSet
557 */
558 public function completionSearch( $search ) {
559 if ( trim( $search ) === '' ) {
560 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
561 }
562 $search = $this->normalizeNamespaces( $search );
563 return $this->processCompletionResults( $search, $this->completionSearchBackend( $search ) );
564 }
565
566 /**
567 * Perform a completion search with variants.
568 * @param string $search
569 * @return SearchSuggestionSet
570 */
571 public function completionSearchWithVariants( $search ) {
572 if ( trim( $search ) === '' ) {
573 return SearchSuggestionSet::emptySuggestionSet(); // Return empty result
574 }
575 $search = $this->normalizeNamespaces( $search );
576
577 $results = $this->completionSearchBackend( $search );
578 $fallbackLimit = $this->limit - $results->getSize();
579 if ( $fallbackLimit > 0 ) {
580 global $wgContLang;
581
582 $fallbackSearches = $wgContLang->autoConvertToAllVariants( $search );
583 $fallbackSearches = array_diff( array_unique( $fallbackSearches ), [ $search ] );
584
585 foreach ( $fallbackSearches as $fbs ) {
586 $this->setLimitOffset( $fallbackLimit );
587 $fallbackSearchResult = $this->completionSearch( $fbs );
588 $results->appendAll( $fallbackSearchResult );
589 $fallbackLimit -= $fallbackSearchResult->getSize();
590 if ( $fallbackLimit <= 0 ) {
591 break;
592 }
593 }
594 }
595 return $this->processCompletionResults( $search, $results );
596 }
597
598 /**
599 * Extract titles from completion results
600 * @param SearchSuggestionSet $completionResults
601 * @return Title[]
602 */
603 public function extractTitles( SearchSuggestionSet $completionResults ) {
604 return $completionResults->map( function ( SearchSuggestion $sugg ) {
605 return $sugg->getSuggestedTitle();
606 } );
607 }
608
609 /**
610 * Process completion search results.
611 * Resolves the titles and rescores.
612 * @param string $search
613 * @param SearchSuggestionSet $suggestions
614 * @return SearchSuggestionSet
615 */
616 protected function processCompletionResults( $search, SearchSuggestionSet $suggestions ) {
617 $search = trim( $search );
618 // preload the titles with LinkBatch
619 $titles = $suggestions->map( function ( SearchSuggestion $sugg ) {
620 return $sugg->getSuggestedTitle();
621 } );
622 $lb = new LinkBatch( $titles );
623 $lb->setCaller( __METHOD__ );
624 $lb->execute();
625
626 $results = $suggestions->map( function ( SearchSuggestion $sugg ) {
627 return $sugg->getSuggestedTitle()->getPrefixedText();
628 } );
629
630 if ( $this->offset === 0 ) {
631 // Rescore results with an exact title match
632 // NOTE: in some cases like cross-namespace redirects
633 // (frequently used as shortcuts e.g. WP:WP on huwiki) some
634 // backends like Cirrus will return no results. We should still
635 // try an exact title match to workaround this limitation
636 $rescorer = new SearchExactMatchRescorer();
637 $rescoredResults = $rescorer->rescore( $search, $this->namespaces, $results, $this->limit );
638 } else {
639 // No need to rescore if offset is not 0
640 // The exact match must have been returned at position 0
641 // if it existed.
642 $rescoredResults = $results;
643 }
644
645 if ( count( $rescoredResults ) > 0 ) {
646 $found = array_search( $rescoredResults[0], $results );
647 if ( $found === false ) {
648 // If the first result is not in the previous array it
649 // means that we found a new exact match
650 $exactMatch = SearchSuggestion::fromTitle( 0, Title::newFromText( $rescoredResults[0] ) );
651 $suggestions->prepend( $exactMatch );
652 $suggestions->shrink( $this->limit );
653 } else {
654 // if the first result is not the same we need to rescore
655 if ( $found > 0 ) {
656 $suggestions->rescore( $found );
657 }
658 }
659 }
660
661 return $suggestions;
662 }
663
664 /**
665 * Simple prefix search for subpages.
666 * @param string $search
667 * @return Title[]
668 */
669 public function defaultPrefixSearch( $search ) {
670 if ( trim( $search ) === '' ) {
671 return [];
672 }
673
674 $search = $this->normalizeNamespaces( $search );
675 return $this->simplePrefixSearch( $search );
676 }
677
678 /**
679 * Call out to simple search backend.
680 * Defaults to TitlePrefixSearch.
681 * @param string $search
682 * @return Title[]
683 */
684 protected function simplePrefixSearch( $search ) {
685 // Use default database prefix search
686 $backend = new TitlePrefixSearch;
687 return $backend->defaultSearchBackend( $this->namespaces, $search, $this->limit, $this->offset );
688 }
689
690 /**
691 * Make a list of searchable namespaces and their canonical names.
692 * @deprecated since 1.27; use SearchEngineConfig::searchableNamespaces()
693 * @return array
694 */
695 public static function searchableNamespaces() {
696 return MediaWikiServices::getInstance()->getSearchEngineConfig()->searchableNamespaces();
697 }
698
699 /**
700 * Extract default namespaces to search from the given user's
701 * settings, returning a list of index numbers.
702 * @deprecated since 1.27; use SearchEngineConfig::userNamespaces()
703 * @param user $user
704 * @return array
705 */
706 public static function userNamespaces( $user ) {
707 return MediaWikiServices::getInstance()->getSearchEngineConfig()->userNamespaces( $user );
708 }
709
710 /**
711 * An array of namespaces indexes to be searched by default
712 * @deprecated since 1.27; use SearchEngineConfig::defaultNamespaces()
713 * @return array
714 */
715 public static function defaultNamespaces() {
716 return MediaWikiServices::getInstance()->getSearchEngineConfig()->defaultNamespaces();
717 }
718
719 /**
720 * Get a list of namespace names useful for showing in tooltips
721 * and preferences
722 * @deprecated since 1.27; use SearchEngineConfig::namespacesAsText()
723 * @param array $namespaces
724 * @return array
725 */
726 public static function namespacesAsText( $namespaces ) {
727 return MediaWikiServices::getInstance()->getSearchEngineConfig()->namespacesAsText( $namespaces );
728 }
729
730 /**
731 * Load up the appropriate search engine class for the currently
732 * active database backend, and return a configured instance.
733 * @deprecated since 1.27; Use SearchEngineFactory::create
734 * @param string $type Type of search backend, if not the default
735 * @return SearchEngine
736 */
737 public static function create( $type = null ) {
738 return MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $type );
739 }
740
741 /**
742 * Return the search engines we support. If only $wgSearchType
743 * is set, it'll be an array of just that one item.
744 * @deprecated since 1.27; use SearchEngineConfig::getSearchTypes()
745 * @return array
746 */
747 public static function getSearchTypes() {
748 return MediaWikiServices::getInstance()->getSearchEngineConfig()->getSearchTypes();
749 }
750
751 /**
752 * Get a list of supported profiles.
753 * Some search engine implementations may expose specific profiles to fine-tune
754 * its behaviors.
755 * The profile can be passed as a feature data with setFeatureData( $profileType, $profileName )
756 * The array returned by this function contains the following keys:
757 * - name: the profile name to use with setFeatureData
758 * - desc-message: the i18n description
759 * - default: set to true if this profile is the default
760 *
761 * @since 1.28
762 * @param string $profileType the type of profiles
763 * @param User|null $user the user requesting the list of profiles
764 * @return array|null the list of profiles or null if none available
765 */
766 public function getProfiles( $profileType, User $user = null ) {
767 return null;
768 }
769
770 /**
771 * Create a search field definition.
772 * Specific search engines should override this method to create search fields.
773 * @param string $name
774 * @param int $type One of the types in SearchIndexField::INDEX_TYPE_*
775 * @return SearchIndexField
776 * @since 1.28
777 */
778 public function makeSearchFieldMapping( $name, $type ) {
779 return new NullIndexField();
780 }
781
782 /**
783 * Get fields for search index
784 * @since 1.28
785 * @return SearchIndexField[] Index field definitions for all content handlers
786 */
787 public function getSearchIndexFields() {
788 $models = ContentHandler::getContentModels();
789 $fields = [];
790 $seenHandlers = new SplObjectStorage();
791 foreach ( $models as $model ) {
792 try {
793 $handler = ContentHandler::getForModelID( $model );
794 }
795 catch ( MWUnknownContentModelException $e ) {
796 // If we can find no handler, ignore it
797 continue;
798 }
799 // Several models can have the same handler, so avoid processing it repeatedly
800 if ( $seenHandlers->contains( $handler ) ) {
801 // We already did this one
802 continue;
803 }
804 $seenHandlers->attach( $handler );
805 $handlerFields = $handler->getFieldsForSearchIndex( $this );
806 foreach ( $handlerFields as $fieldName => $fieldData ) {
807 if ( empty( $fields[$fieldName] ) ) {
808 $fields[$fieldName] = $fieldData;
809 } else {
810 // TODO: do we allow some clashes with the same type or reject all of them?
811 $mergeDef = $fields[$fieldName]->merge( $fieldData );
812 if ( !$mergeDef ) {
813 throw new InvalidArgumentException( "Duplicate field $fieldName for model $model" );
814 }
815 $fields[$fieldName] = $mergeDef;
816 }
817 }
818 }
819 // Hook to allow extensions to produce search mapping fields
820 Hooks::run( 'SearchIndexFields', [ &$fields, $this ] );
821 return $fields;
822 }
823
824 /**
825 * Augment search results with extra data.
826 *
827 * @param SearchResultSet $resultSet
828 */
829 public function augmentSearchResults( SearchResultSet $resultSet ) {
830 $setAugmentors = [];
831 $rowAugmentors = [];
832 Hooks::run( "SearchResultsAugment", [ &$setAugmentors, &$rowAugmentors ] );
833
834 if ( !$setAugmentors && !$rowAugmentors ) {
835 // We're done here
836 return;
837 }
838
839 // Convert row augmentors to set augmentor
840 foreach ( $rowAugmentors as $name => $row ) {
841 if ( isset( $setAugmentors[$name] ) ) {
842 throw new InvalidArgumentException( "Both row and set augmentors are defined for $name" );
843 }
844 $setAugmentors[$name] = new PerRowAugmentor( $row );
845 }
846
847 foreach ( $setAugmentors as $name => $augmentor ) {
848 $data = $augmentor->augmentAll( $resultSet );
849 if ( $data ) {
850 $resultSet->setAugmentedData( $name, $data );
851 }
852 }
853 }
854 }
855
856 /**
857 * Dummy class to be used when non-supported Database engine is present.
858 * @todo FIXME: Dummy class should probably try something at least mildly useful,
859 * such as a LIKE search through titles.
860 * @ingroup Search
861 */
862 class SearchEngineDummy extends SearchEngine {
863 // no-op
864 }