3 * Implements Special:Search
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
23 * @ingroup SpecialPage
26 use MediaWiki\MediaWikiServices
;
27 use MediaWiki\Widget\Search\BasicSearchResultSetWidget
;
28 use MediaWiki\Widget\Search\FullSearchResultWidget
;
29 use MediaWiki\Widget\Search\InterwikiSearchResultWidget
;
30 use MediaWiki\Widget\Search\InterwikiSearchResultSetWidget
;
31 use MediaWiki\Widget\Search\SimpleSearchResultWidget
;
32 use MediaWiki\Widget\Search\SimpleSearchResultSetWidget
;
35 * implements Special:Search - Run text & title search and display the output
36 * @ingroup SpecialPage
38 class SpecialSearch
extends SpecialPage
{
40 * Current search profile. Search profile is just a name that identifies
41 * the active search tab on the search page (content, discussions...)
42 * For users tt replaces the set of enabled namespaces from the query
43 * string when applicable. Extensions can add new profiles with hooks
44 * with custom search options just for that profile.
49 /** @var SearchEngine Search engine */
50 protected $searchEngine;
52 /** @var string Search engine type, if not default */
53 protected $searchEngineType;
55 /** @var array For links */
56 protected $extraParams = [];
59 * @var string The prefix url parameter. Set on the searcher and the
60 * is expected to treat it as prefix filter on titles.
67 protected $limit, $offset;
72 protected $namespaces;
87 protected $runSuggestion = true;
90 * Search engine configurations.
91 * @var SearchEngineConfig
93 protected $searchConfig;
95 const NAMESPACES_CURRENT
= 'sense';
97 public function __construct() {
98 parent
::__construct( 'Search' );
99 $this->searchConfig
= MediaWikiServices
::getInstance()->getSearchEngineConfig();
107 public function execute( $par ) {
108 $request = $this->getRequest();
109 $out = $this->getOutput();
111 // Fetch the search term
112 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
114 // Historically search terms have been accepted not only in the search query
115 // parameter, but also as part of the primary url. This can have PII implications
116 // in releasing page view data. As such issue a 301 redirect to the correct
118 if ( strlen( $par ) && !strlen( $term ) ) {
119 $query = $request->getValues();
120 unset( $query['title'] );
121 // Strip underscores from title parameter; most of the time we'll want
122 // text form here. But don't strip underscores from actual text params!
123 $query['search'] = str_replace( '_', ' ', $par );
124 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
128 // Need to load selected namespaces before handling nsRemember
130 // TODO: This performs database actions on GET request, which is going to
131 // be a problem for our multi-datacenter work.
132 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
133 $this->saveNamespaces();
134 // Remove the token from the URL to prevent the user from inadvertently
135 // exposing it (e.g. by pasting it into a public wiki page) or undoing
136 // later settings changes (e.g. by reloading the page).
137 $query = $request->getValues();
138 unset( $query['title'], $query['nsRemember'] );
139 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
143 $this->searchEngineType
= $request->getVal( 'srbackend' );
145 !$request->getVal( 'fulltext' ) &&
146 $request->getVal( 'offset' ) === null
148 $url = $this->goResult( $term );
149 if ( $url !== null ) {
151 $out->redirect( $url );
154 // No match. If it could plausibly be a title
155 // run the No go match hook.
156 $title = Title
::newFromText( $term );
157 if ( !is_null( $title ) ) {
158 Hooks
::run( 'SpecialSearchNogomatch', [ &$title ] );
162 $this->setupPage( $term );
164 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
165 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
166 if ( $searchForwardUrl ) {
167 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
168 $out->redirect( $url );
173 $this->msg( 'search-external' )->escaped() .
175 "<p class='mw-searchdisabled'>" .
176 $this->msg( 'searchdisabled' )->escaped() .
178 $this->msg( 'googlesearch' )->rawParams(
179 htmlspecialchars( $term ),
181 $this->msg( 'searchbutton' )->escaped()
190 $this->showResults( $term );
194 * Set up basic search parameters from the request and user settings.
196 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
198 public function load() {
199 $request = $this->getRequest();
200 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
201 $this->mPrefix
= $request->getVal( 'prefix', '' );
202 if ( $this->mPrefix
!== '' ) {
203 $this->setExtraParam( 'prefix', $this->mPrefix
);
206 $this->sort
= $request->getVal( 'sort', SearchEngine
::DEFAULT_SORT
);
207 if ( $this->sort
!== SearchEngine
::DEFAULT_SORT
) {
208 $this->setExtraParam( 'sort', $this->sort
);
211 $user = $this->getUser();
213 # Extract manually requested namespaces
214 $nslist = $this->powerSearch( $request );
215 if ( !count( $nslist ) ) {
216 # Fallback to user preference
217 $nslist = $this->searchConfig
->userNamespaces( $user );
221 if ( !count( $nslist ) ) {
222 $profile = 'default';
225 $profile = $request->getVal( 'profile', $profile );
226 $profiles = $this->getSearchProfiles();
227 if ( $profile === null ) {
228 // BC with old request format
229 $profile = 'advanced';
230 foreach ( $profiles as $key => $data ) {
231 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
235 $this->namespaces
= $nslist;
236 } elseif ( $profile === 'advanced' ) {
237 $this->namespaces
= $nslist;
239 if ( isset( $profiles[$profile]['namespaces'] ) ) {
240 $this->namespaces
= $profiles[$profile]['namespaces'];
242 // Unknown profile requested
243 $profile = 'default';
244 $this->namespaces
= $profiles['default']['namespaces'];
248 $this->fulltext
= $request->getVal( 'fulltext' );
249 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
250 $this->profile
= $profile;
254 * If an exact title match can be found, jump straight ahead to it.
256 * @param string $term
257 * @return string|null The url to redirect to, or null if no redirect.
259 public function goResult( $term ) {
260 # If the string cannot be used to create a title
261 if ( is_null( Title
::newFromText( $term ) ) ) {
264 # If there's an exact or very near match, jump right there.
265 $title = $this->getSearchEngine()
266 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
267 if ( is_null( $title ) ) {
271 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
275 return $url ??
$title->getFullUrlForRedirect();
279 * @param string $term
281 public function showResults( $term ) {
282 if ( $this->searchEngineType
!== null ) {
283 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
286 $out = $this->getOutput();
287 $formWidget = new MediaWiki\Widget\Search\
SearchFormWidget(
290 $this->getSearchProfiles()
292 $filePrefix = MediaWikiServices
::getInstance()->getContentLanguage()->
293 getFormattedNsText( NS_FILE
) . ':';
294 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
295 // Empty query -- straight view of search form
296 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
297 # Hook requested termination
301 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
302 // only do the form render here for the empty $term case. Rendering
303 // the form when a search is provided is repeated below.
304 $out->addHTML( $formWidget->render(
305 $this->profile
, $term, 0, 0, $this->offset
, $this->isPowerSearch()
310 $search = $this->getSearchEngine();
311 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
312 $search->setLimitOffset( $this->limit
, $this->offset
);
313 $search->setNamespaces( $this->namespaces
);
314 $search->setSort( $this->sort
);
315 $search->prefix
= $this->mPrefix
;
317 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
318 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
319 # Hook requested termination
323 $title = Title
::newFromText( $term );
324 $showSuggestion = $title === null ||
!$title->isKnown();
325 $search->setShowSuggestion( $showSuggestion );
327 $rewritten = $search->transformSearchTerm( $term );
328 if ( $rewritten !== $term ) {
330 wfDeprecated( 'SearchEngine::transformSearchTerm() (overridden by ' .
331 get_class( $search ) . ')', '1.32' );
334 $rewritten = $search->replacePrefixes( $term );
335 if ( $rewritten !== $term ) {
336 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
337 get_class( $search ) . ')', '1.32' );
340 // fetch search results
341 $titleMatches = $search->searchTitle( $rewritten );
342 $textMatches = $search->searchText( $rewritten );
345 if ( $textMatches instanceof Status
) {
346 $textStatus = $textMatches;
347 $textMatches = $textStatus->getValue();
350 // Get number of results
351 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
352 if ( $titleMatches ) {
353 $titleMatchesNum = $titleMatches->numRows();
354 $numTitleMatches = $titleMatches->getTotalHits();
356 if ( $textMatches ) {
357 $textMatchesNum = $textMatches->numRows();
358 $numTextMatches = $textMatches->getTotalHits();
359 if ( $textMatchesNum > 0 ) {
360 $search->augmentSearchResults( $textMatches );
363 $num = $titleMatchesNum +
$textMatchesNum;
364 $totalRes = $numTitleMatches +
$numTextMatches;
366 // start rendering the page
368 $out->addHTML( $formWidget->render(
369 $this->profile
, $term, $num, $totalRes, $this->offset
, $this->isPowerSearch()
372 // did you mean... suggestions
373 if ( $textMatches ) {
374 $dymWidget = new MediaWiki\Widget\Search\
DidYouMeanWidget( $this );
375 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
378 $hasErrors = $textStatus && $textStatus->getErrors() !== [];
379 $hasOtherResults = $textMatches &&
380 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
382 if ( $textMatches && $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
383 $out->addHTML( '<div class="searchresults mw-searchresults-has-iw">' );
385 $out->addHTML( '<div class="searchresults">' );
389 list( $error, $warning ) = $textStatus->splitByErrorType();
390 if ( $error->getErrors() ) {
391 $out->addHTML( Html
::errorBox(
392 $error->getHTML( 'search-error' )
395 if ( $warning->getErrors() ) {
396 $out->addHTML( Html
::warningBox(
397 $warning->getHTML( 'search-warning' )
402 // Show the create link ahead
403 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
405 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
407 // If we have no results and have not already displayed an error message
408 if ( $num === 0 && !$hasErrors ) {
409 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
410 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
411 wfEscapeWikiText( $term )
415 // Although $num might be 0 there can still be secondary or inline
416 // results to display.
417 $linkRenderer = $this->getLinkRenderer();
418 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
420 // Default (null) on. Can be explicitly disabled.
421 if ( $search->getFeatureData( 'enable-new-crossproject-page' ) !== false ) {
422 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
423 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
425 $sidebarResultWidget,
427 MediaWikiServices
::getInstance()->getInterwikiLookup(),
428 $search->getFeatureData( 'show-multimedia-search-results' )
431 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
432 $sidebarResultsWidget = new SimpleSearchResultSetWidget(
434 $sidebarResultWidget,
436 MediaWikiServices
::getInstance()->getInterwikiLookup()
440 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
442 $out->addHTML( $widget->render(
443 $term, $this->offset
, $titleMatches, $textMatches
446 if ( $titleMatches ) {
447 $titleMatches->free();
450 if ( $textMatches ) {
451 $textMatches->free();
454 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
457 if ( $totalRes > $this->limit ||
$this->offset
) {
458 // Allow matches to define the correct offset, as interleaved
459 // AB testing may require a different next page offset.
460 if ( $textMatches && $textMatches->getOffset() !== null ) {
461 $offset = $textMatches->getOffset();
463 $offset = $this->offset
;
466 $prevnext = $this->getLanguage()->viewPrevNext(
467 $this->getPageTitle(),
470 $this->powerSearchOptions() +
[ 'search' => $term ],
471 $this->limit +
$this->offset
>= $totalRes
473 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
476 // Close <div class='searchresults'>
477 $out->addHTML( "</div>" );
479 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
483 * @param Title $title
484 * @param int $num The number of search results found
485 * @param null|SearchResultSet $titleMatches Results from title search
486 * @param null|SearchResultSet $textMatches Results from text search
488 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
489 // show direct page/create link if applicable
491 // Check DBkey !== '' in case of fragment link only.
492 if ( is_null( $title ) ||
$title->getDBkey() === ''
493 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
494 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
497 // preserve the paragraph for margins etc...
498 $this->getOutput()->addHTML( '<p></p>' );
503 $messageName = 'searchmenu-new-nocreate';
504 $linkClass = 'mw-search-createlink';
506 if ( !$title->isExternal() ) {
507 if ( $title->isKnown() ) {
508 $messageName = 'searchmenu-exists';
509 $linkClass = 'mw-search-exists';
510 } elseif ( ContentHandler
::getForTitle( $title )->supportsDirectEditing()
511 && $title->quickUserCan( 'create', $this->getUser() )
513 $messageName = 'searchmenu-new';
519 wfEscapeWikiText( $title->getPrefixedText() ),
520 Message
::numParam( $num )
522 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
524 // Extensions using the hook might still return an empty $messageName
525 if ( $messageName ) {
526 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
528 // preserve the paragraph for margins etc...
529 $this->getOutput()->addHTML( '<p></p>' );
534 * Sets up everything for the HTML output page including styles, javascript,
537 * @param string $term
539 protected function setupPage( $term ) {
540 $out = $this->getOutput();
543 $this->outputHeader();
544 // TODO: Is this true? The namespace remember uses a user token
546 $out->allowClickjacking();
547 $this->addHelpLink( 'Help:Searching' );
549 if ( strval( $term ) !== '' ) {
550 $out->setPageTitle( $this->msg( 'searchresults' ) );
551 $out->setHTMLTitle( $this->msg( 'pagetitle' )
552 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
553 ->inContentLanguage()->text()
557 if ( $this->mPrefix
!== '' ) {
558 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix
);
559 $params = $this->powerSearchOptions();
560 unset( $params['prefix'] );
567 $subtitle .= Xml
::element(
570 'href' => $this->getPageTitle()->getLocalURL( $params ),
571 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
573 $this->msg( 'search-filter-title-prefix-reset' )->text()
576 $out->setSubtitle( $subtitle );
579 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
580 $out->addModules( 'mediawiki.special.search' );
581 $out->addModuleStyles( [
582 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
583 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
588 * Return true if current search is a power (advanced) search
592 protected function isPowerSearch() {
593 return $this->profile
=== 'advanced';
597 * Extract "power search" namespace settings from the request object,
598 * returning a list of index numbers to search.
600 * @param WebRequest &$request
603 protected function powerSearch( &$request ) {
605 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
606 if ( $request->getCheck( 'ns' . $ns ) ) {
615 * Reconstruct the 'power search' options for links
616 * TODO: Instead of exposing this publicly, could we instead expose
617 * a function for creating search links?
621 public function powerSearchOptions() {
623 if ( $this->isPowerSearch() ) {
624 foreach ( $this->namespaces
as $n ) {
628 $opt['profile'] = $this->profile
;
631 return $opt +
$this->extraParams
;
635 * Save namespace preferences when we're supposed to
637 * @return bool Whether we wrote something
639 protected function saveNamespaces() {
640 $user = $this->getUser();
641 $request = $this->getRequest();
643 if ( $user->isLoggedIn() &&
644 $user->matchEditToken(
645 $request->getVal( 'nsRemember' ),
650 // Reset namespace preferences: namespaces are not searched
651 // when they're not mentioned in the URL parameters.
652 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
653 $user->setOption( 'searchNs' . $n, false );
655 // The request parameters include all the namespaces to be searched.
656 // Even if they're the same as an existing profile, they're not eaten.
657 foreach ( $this->namespaces
as $n ) {
658 $user->setOption( 'searchNs' . $n, true );
661 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
662 $user->saveSettings();
674 protected function getSearchProfiles() {
675 // Builds list of Search Types (profiles)
676 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
677 $defaultNs = $this->searchConfig
->defaultNamespaces();
680 'message' => 'searchprofile-articles',
681 'tooltip' => 'searchprofile-articles-tooltip',
682 'namespaces' => $defaultNs,
683 'namespace-messages' => $this->searchConfig
->namespacesAsText(
688 'message' => 'searchprofile-images',
689 'tooltip' => 'searchprofile-images-tooltip',
690 'namespaces' => [ NS_FILE
],
693 'message' => 'searchprofile-everything',
694 'tooltip' => 'searchprofile-everything-tooltip',
695 'namespaces' => $nsAllSet,
698 'message' => 'searchprofile-advanced',
699 'tooltip' => 'searchprofile-advanced-tooltip',
700 'namespaces' => self
::NAMESPACES_CURRENT
,
704 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
706 foreach ( $profiles as &$data ) {
707 if ( !is_array( $data['namespaces'] ) ) {
710 sort( $data['namespaces'] );
719 * @return SearchEngine
721 public function getSearchEngine() {
722 if ( $this->searchEngine
=== null ) {
723 $services = MediaWikiServices
::getInstance();
724 $this->searchEngine
= $this->searchEngineType ?
725 $services->getSearchEngineFactory()->create( $this->searchEngineType
) :
726 $services->newSearchEngine();
729 return $this->searchEngine
;
733 * Current search profile.
734 * @return null|string
736 function getProfile() {
737 return $this->profile
;
741 * Current namespaces.
744 function getNamespaces() {
745 return $this->namespaces
;
749 * Users of hook SpecialSearchSetupEngine can use this to
750 * add more params to links to not lose selection when
751 * user navigates search results.
755 * @param mixed $value
757 public function setExtraParam( $key, $value ) {
758 $this->extraParams
[$key] = $value;
762 * The prefix value send to Special:Search using the 'prefix' URI param
763 * It means that the user is willing to search for pages whose titles start with
765 * (Used by the InputBox extension)
769 public function getPrefix() {
770 return $this->mPrefix
;
773 protected function getGroupName() {