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