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;
82 protected $sort = SearchEngine
::DEFAULT_SORT
;
87 protected $runSuggestion = true;
90 * Search engine configurations.
91 * @var SearchEngineConfig
93 protected $searchConfig;
96 * @var Status Holds any parameter validation errors that should
97 * be displayed back to the user.
101 const NAMESPACES_CURRENT
= 'sense';
103 public function __construct() {
104 parent
::__construct( 'Search' );
105 $this->searchConfig
= MediaWikiServices
::getInstance()->getSearchEngineConfig();
111 * @param string|null $par
113 public function execute( $par ) {
114 $request = $this->getRequest();
115 $out = $this->getOutput();
117 // Fetch the search term
118 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
120 // Historically search terms have been accepted not only in the search query
121 // parameter, but also as part of the primary url. This can have PII implications
122 // in releasing page view data. As such issue a 301 redirect to the correct
124 if ( $par !== null && $par !== '' && $term === '' ) {
125 $query = $request->getValues();
126 unset( $query['title'] );
127 // Strip underscores from title parameter; most of the time we'll want
128 // text form here. But don't strip underscores from actual text params!
129 $query['search'] = str_replace( '_', ' ', $par );
130 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
134 // Need to load selected namespaces before handling nsRemember
136 // TODO: This performs database actions on GET request, which is going to
137 // be a problem for our multi-datacenter work.
138 if ( $request->getCheck( 'nsRemember' ) ) {
139 $this->saveNamespaces();
140 // Remove the token from the URL to prevent the user from inadvertently
141 // exposing it (e.g. by pasting it into a public wiki page) or undoing
142 // later settings changes (e.g. by reloading the page).
143 $query = $request->getValues();
144 unset( $query['title'], $query['nsRemember'] );
145 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
149 $this->searchEngineType
= $request->getVal( 'srbackend' );
150 if ( !$request->getVal( 'fulltext' ) && !$request->getCheck( 'offset' ) ) {
151 $url = $this->goResult( $term );
152 if ( $url !== null ) {
154 $out->redirect( $url );
157 // No match. If it could plausibly be a title
158 // run the No go match hook.
159 $title = Title
::newFromText( $term );
160 if ( !is_null( $title ) ) {
161 Hooks
::run( 'SpecialSearchNogomatch', [ &$title ] );
165 $this->setupPage( $term );
167 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
168 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
169 if ( $searchForwardUrl ) {
170 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
171 $out->redirect( $url );
173 $this->showGoogleSearch( $term );
179 $this->showResults( $term );
183 * Output a google search form if search is disabled
185 * @param string $term Search term
186 * @todo FIXME Maybe we should get rid of this raw html message at some future time
187 * @suppress SecurityCheck-XSS
189 private function showGoogleSearch( $term ) {
190 $this->getOutput()->addHTML(
193 $this->msg( 'search-external' )->escaped() .
195 "<p class='mw-searchdisabled'>" .
196 $this->msg( 'searchdisabled' )->escaped() .
198 $this->msg( 'googlesearch' )->rawParams(
199 htmlspecialchars( $term ),
201 $this->msg( 'searchbutton' )->escaped()
208 * Set up basic search parameters from the request and user settings.
210 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
212 public function load() {
213 $this->loadStatus
= new Status();
215 $request = $this->getRequest();
216 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
217 $this->mPrefix
= $request->getVal( 'prefix', '' );
218 if ( $this->mPrefix
!== '' ) {
219 $this->setExtraParam( 'prefix', $this->mPrefix
);
222 $sort = $request->getVal( 'sort', SearchEngine
::DEFAULT_SORT
);
223 $validSorts = $this->getSearchEngine()->getValidSorts();
224 if ( !in_array( $sort, $validSorts ) ) {
225 $this->loadStatus
->warning( 'search-invalid-sort-order', $sort,
226 implode( ', ', $validSorts ) );
227 } elseif ( $sort !== $this->sort
) {
229 $this->setExtraParam( 'sort', $this->sort
);
232 $user = $this->getUser();
234 # Extract manually requested namespaces
235 $nslist = $this->powerSearch( $request );
236 if ( $nslist === [] ) {
237 # Fallback to user preference
238 $nslist = $this->searchConfig
->userNamespaces( $user );
242 if ( $nslist === [] ) {
243 $profile = 'default';
246 $profile = $request->getVal( 'profile', $profile );
247 $profiles = $this->getSearchProfiles();
248 if ( $profile === null ) {
249 // BC with old request format
250 $profile = 'advanced';
251 foreach ( $profiles as $key => $data ) {
252 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
256 $this->namespaces
= $nslist;
257 } elseif ( $profile === 'advanced' ) {
258 $this->namespaces
= $nslist;
259 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
260 $this->namespaces
= $profiles[$profile]['namespaces'];
262 // Unknown profile requested
263 $this->loadStatus
->warning( 'search-unknown-profile', $profile );
264 $profile = 'default';
265 $this->namespaces
= $profiles['default']['namespaces'];
268 $this->fulltext
= $request->getVal( 'fulltext' );
269 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
270 $this->profile
= $profile;
274 * If an exact title match can be found, jump straight ahead to it.
276 * @param string $term
277 * @return string|null The url to redirect to, or null if no redirect.
279 public function goResult( $term ) {
280 # If the string cannot be used to create a title
281 if ( is_null( Title
::newFromText( $term ) ) ) {
284 # If there's an exact or very near match, jump right there.
285 $title = $this->getSearchEngine()
286 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
287 if ( is_null( $title ) ) {
291 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
295 return $url ??
$title->getFullUrlForRedirect();
299 * @param string $term
301 public function showResults( $term ) {
302 if ( $this->searchEngineType
!== null ) {
303 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
306 $out = $this->getOutput();
307 $widgetOptions = $this->getConfig()->get( 'SpecialSearchFormOptions' );
308 $formWidget = new MediaWiki\Widget\Search\
SearchFormWidget(
311 $this->getSearchProfiles()
313 $filePrefix = MediaWikiServices
::getInstance()->getContentLanguage()->
314 getFormattedNsText( NS_FILE
) . ':';
315 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
316 // Empty query -- straight view of search form
317 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
318 # Hook requested termination
322 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
323 // only do the form render here for the empty $term case. Rendering
324 // the form when a search is provided is repeated below.
325 $out->addHTML( $formWidget->render(
326 $this->profile
, $term, 0, 0, $this->offset
, $this->isPowerSearch(), $widgetOptions
331 $engine = $this->getSearchEngine();
332 $engine->setFeatureData( 'rewrite', $this->runSuggestion
);
333 $engine->setLimitOffset( $this->limit
, $this->offset
);
334 $engine->setNamespaces( $this->namespaces
);
335 $engine->setSort( $this->sort
);
336 $engine->prefix
= $this->mPrefix
;
338 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $engine ] );
339 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
340 # Hook requested termination
344 $title = Title
::newFromText( $term );
345 $showSuggestion = $title === null ||
!$title->isKnown();
346 $engine->setShowSuggestion( $showSuggestion );
348 $rewritten = $engine->replacePrefixes( $term );
349 if ( $rewritten !== $term ) {
350 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
351 get_class( $engine ) . ')', '1.32' );
354 // fetch search results
355 $titleMatches = $engine->searchTitle( $rewritten );
356 $textMatches = $engine->searchText( $rewritten );
359 if ( $textMatches instanceof Status
) {
360 $textStatus = $textMatches;
361 $textMatches = $textStatus->getValue();
364 // Get number of results
365 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
366 if ( $titleMatches ) {
367 $titleMatchesNum = $titleMatches->numRows();
368 $numTitleMatches = $titleMatches->getTotalHits();
370 if ( $textMatches ) {
371 $textMatchesNum = $textMatches->numRows();
372 $numTextMatches = $textMatches->getTotalHits();
373 if ( $textMatchesNum > 0 ) {
374 $engine->augmentSearchResults( $textMatches );
377 $num = $titleMatchesNum +
$textMatchesNum;
378 $totalRes = $numTitleMatches +
$numTextMatches;
380 // start rendering the page
382 $out->addHTML( $formWidget->render(
383 $this->profile
, $term, $num, $totalRes, $this->offset
, $this->isPowerSearch(), $widgetOptions
386 // did you mean... suggestions
387 if ( $textMatches ) {
388 $dymWidget = new MediaWiki\Widget\Search\
DidYouMeanWidget( $this );
389 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
392 $hasSearchErrors = $textStatus && $textStatus->getErrors() !== [];
393 $hasOtherResults = $textMatches &&
394 $textMatches->hasInterwikiResults( ISearchResultSet
::INLINE_RESULTS
);
396 if ( $textMatches && $textMatches->hasInterwikiResults( ISearchResultSet
::SECONDARY_RESULTS
) ) {
397 $out->addHTML( '<div class="searchresults mw-searchresults-has-iw">' );
399 $out->addHTML( '<div class="searchresults">' );
402 if ( $hasSearchErrors ||
$this->loadStatus
->getErrors() ) {
403 if ( $textStatus === null ) {
404 $textStatus = $this->loadStatus
;
406 $textStatus->merge( $this->loadStatus
);
408 list( $error, $warning ) = $textStatus->splitByErrorType();
409 if ( $error->getErrors() ) {
410 $out->addHTML( Html
::errorBox(
411 $error->getHTML( 'search-error' )
414 if ( $warning->getErrors() ) {
415 $out->addHTML( Html
::warningBox(
416 $warning->getHTML( 'search-warning' )
421 // Show the create link ahead
422 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
424 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
426 // If we have no results and have not already displayed an error message
427 if ( $num === 0 && !$hasSearchErrors ) {
428 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
429 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
430 wfEscapeWikiText( $term )
434 // Although $num might be 0 there can still be secondary or inline
435 // results to display.
436 $linkRenderer = $this->getLinkRenderer();
437 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
439 // Default (null) on. Can be explicitly disabled.
440 if ( $engine->getFeatureData( 'enable-new-crossproject-page' ) !== false ) {
441 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
442 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
444 $sidebarResultWidget,
446 MediaWikiServices
::getInstance()->getInterwikiLookup(),
447 $engine->getFeatureData( 'show-multimedia-search-results' )
450 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
451 $sidebarResultsWidget = new SimpleSearchResultSetWidget(
453 $sidebarResultWidget,
455 MediaWikiServices
::getInstance()->getInterwikiLookup()
459 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
461 $out->addHTML( $widget->render(
462 $term, $this->offset
, $titleMatches, $textMatches
465 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
468 if ( $totalRes > $this->limit ||
$this->offset
) {
469 // Allow matches to define the correct offset, as interleaved
470 // AB testing may require a different next page offset.
471 if ( $textMatches && $textMatches->getOffset() !== null ) {
472 $offset = $textMatches->getOffset();
474 $offset = $this->offset
;
477 $prevNext = $this->buildPrevNextNavigation(
480 $this->powerSearchOptions() +
[ 'search' => $term ],
481 $this->limit +
$this->offset
>= $totalRes
483 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevNext}</p>\n" );
486 // Close <div class='searchresults'>
487 $out->addHTML( "</div>" );
489 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
493 * @param Title $title
494 * @param int $num The number of search results found
495 * @param null|ISearchResultSet $titleMatches Results from title search
496 * @param null|ISearchResultSet $textMatches Results from text search
498 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
499 // show direct page/create link if applicable
501 // Check DBkey !== '' in case of fragment link only.
502 if ( is_null( $title ) ||
$title->getDBkey() === ''
503 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
504 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
507 // preserve the paragraph for margins etc...
508 $this->getOutput()->addHTML( '<p></p>' );
513 $messageName = 'searchmenu-new-nocreate';
514 $linkClass = 'mw-search-createlink';
516 if ( !$title->isExternal() ) {
517 if ( $title->isKnown() ) {
518 $messageName = 'searchmenu-exists';
519 $linkClass = 'mw-search-exists';
520 } elseif ( ContentHandler
::getForTitle( $title )->supportsDirectEditing()
521 && MediaWikiServices
::getInstance()->getPermissionManager()->quickUserCan( 'create',
522 $this->getUser(), $title )
524 $messageName = 'searchmenu-new';
530 wfEscapeWikiText( $title->getPrefixedText() ),
531 Message
::numParam( $num )
533 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
535 // Extensions using the hook might still return an empty $messageName
536 if ( $messageName ) {
537 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
539 // preserve the paragraph for margins etc...
540 $this->getOutput()->addHTML( '<p></p>' );
545 * Sets up everything for the HTML output page including styles, javascript,
548 * @param string $term
550 protected function setupPage( $term ) {
551 $out = $this->getOutput();
554 $this->outputHeader();
555 // TODO: Is this true? The namespace remember uses a user token
557 $out->allowClickjacking();
558 $this->addHelpLink( 'Help:Searching' );
560 if ( strval( $term ) !== '' ) {
561 $out->setPageTitle( $this->msg( 'searchresults' ) );
562 $out->setHTMLTitle( $this->msg( 'pagetitle' )
563 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
564 ->inContentLanguage()->text()
568 if ( $this->mPrefix
!== '' ) {
569 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix
);
570 $params = $this->powerSearchOptions();
571 unset( $params['prefix'] );
578 $subtitle .= Xml
::element(
581 'href' => $this->getPageTitle()->getLocalURL( $params ),
582 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
584 $this->msg( 'search-filter-title-prefix-reset' )->text()
587 $out->setSubtitle( $subtitle );
590 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
591 $out->addModules( 'mediawiki.special.search' );
592 $out->addModuleStyles( [
593 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
594 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
599 * Return true if current search is a power (advanced) search
603 protected function isPowerSearch() {
604 return $this->profile
=== 'advanced';
608 * Extract "power search" namespace settings from the request object,
609 * returning a list of index numbers to search.
611 * @param WebRequest &$request
614 protected function powerSearch( &$request ) {
616 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
617 if ( $request->getCheck( 'ns' . $ns ) ) {
626 * Reconstruct the 'power search' options for links
627 * TODO: Instead of exposing this publicly, could we instead expose
628 * a function for creating search links?
632 public function powerSearchOptions() {
634 if ( $this->isPowerSearch() ) {
635 foreach ( $this->namespaces
as $n ) {
639 $opt['profile'] = $this->profile
;
642 return $opt +
$this->extraParams
;
646 * Save namespace preferences when we're supposed to
648 * @return bool Whether we wrote something
650 protected function saveNamespaces() {
651 $user = $this->getUser();
652 $request = $this->getRequest();
654 if ( $user->isLoggedIn() &&
655 $user->matchEditToken(
656 $request->getVal( 'nsRemember' ),
661 // Reset namespace preferences: namespaces are not searched
662 // when they're not mentioned in the URL parameters.
663 foreach ( MediaWikiServices
::getInstance()->getNamespaceInfo()->getValidNamespaces()
666 $user->setOption( 'searchNs' . $n, false );
668 // The request parameters include all the namespaces to be searched.
669 // Even if they're the same as an existing profile, they're not eaten.
670 foreach ( $this->namespaces
as $n ) {
671 $user->setOption( 'searchNs' . $n, true );
674 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
675 $user->saveSettings();
687 protected function getSearchProfiles() {
688 // Builds list of Search Types (profiles)
689 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
690 $defaultNs = $this->searchConfig
->defaultNamespaces();
693 'message' => 'searchprofile-articles',
694 'tooltip' => 'searchprofile-articles-tooltip',
695 'namespaces' => $defaultNs,
696 'namespace-messages' => $this->searchConfig
->namespacesAsText(
701 'message' => 'searchprofile-images',
702 'tooltip' => 'searchprofile-images-tooltip',
703 'namespaces' => [ NS_FILE
],
706 'message' => 'searchprofile-everything',
707 'tooltip' => 'searchprofile-everything-tooltip',
708 'namespaces' => $nsAllSet,
711 'message' => 'searchprofile-advanced',
712 'tooltip' => 'searchprofile-advanced-tooltip',
713 'namespaces' => self
::NAMESPACES_CURRENT
,
717 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
719 foreach ( $profiles as &$data ) {
720 if ( !is_array( $data['namespaces'] ) ) {
723 sort( $data['namespaces'] );
732 * @return SearchEngine
734 public function getSearchEngine() {
735 if ( $this->searchEngine
=== null ) {
736 $services = MediaWikiServices
::getInstance();
737 $this->searchEngine
= $this->searchEngineType ?
738 $services->getSearchEngineFactory()->create( $this->searchEngineType
) :
739 $services->newSearchEngine();
742 return $this->searchEngine
;
746 * Current search profile.
747 * @return null|string
749 function getProfile() {
750 return $this->profile
;
754 * Current namespaces.
757 function getNamespaces() {
758 return $this->namespaces
;
762 * Users of hook SpecialSearchSetupEngine can use this to
763 * add more params to links to not lose selection when
764 * user navigates search results.
768 * @param mixed $value
770 public function setExtraParam( $key, $value ) {
771 $this->extraParams
[$key] = $value;
775 * The prefix value send to Special:Search using the 'prefix' URI param
776 * It means that the user is willing to search for pages whose titles start with
778 * (Used by the InputBox extension)
782 public function getPrefix() {
783 return $this->mPrefix
;
786 protected function getGroupName() {