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