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