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