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 $runSuggestion = true;
85 * Search engine configurations.
86 * @var SearchEngineConfig
88 protected $searchConfig;
90 const NAMESPACES_CURRENT
= 'sense';
92 public function __construct() {
93 parent
::__construct( 'Search' );
94 $this->searchConfig
= MediaWikiServices
::getInstance()->getSearchEngineConfig();
102 public function execute( $par ) {
103 $request = $this->getRequest();
104 $out = $this->getOutput();
106 // Fetch the search term
107 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
109 // Historically search terms have been accepted not only in the search query
110 // parameter, but also as part of the primary url. This can have PII implications
111 // in releasing page view data. As such issue a 301 redirect to the correct
113 if ( strlen( $par ) && !strlen( $term ) ) {
114 $query = $request->getValues();
115 unset( $query['title'] );
116 // Strip underscores from title parameter; most of the time we'll want
117 // text form here. But don't strip underscores from actual text params!
118 $query['search'] = str_replace( '_', ' ', $par );
119 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
123 // Need to load selected namespaces before handling nsRemember
125 // TODO: This performs database actions on GET request, which is going to
126 // be a problem for our multi-datacenter work.
127 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
128 $this->saveNamespaces();
129 // Remove the token from the URL to prevent the user from inadvertently
130 // exposing it (e.g. by pasting it into a public wiki page) or undoing
131 // later settings changes (e.g. by reloading the page).
132 $query = $request->getValues();
133 unset( $query['title'], $query['nsRemember'] );
134 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
138 $this->searchEngineType
= $request->getVal( 'srbackend' );
140 !$request->getVal( 'fulltext' ) &&
141 $request->getVal( 'offset' ) === null
143 $url = $this->goResult( $term );
144 if ( $url !== null ) {
146 $out->redirect( $url );
149 // No match. If it could plausibly be a title
150 // run the No go match hook.
151 $title = Title
::newFromText( $term );
152 if ( !is_null( $title ) ) {
153 Hooks
::run( 'SpecialSearchNogomatch', [ &$title ] );
157 $this->setupPage( $term );
159 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
160 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
161 if ( $searchForwardUrl ) {
162 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
163 $out->redirect( $url );
168 $this->msg( 'search-external' )->escaped() .
170 "<p class='mw-searchdisabled'>" .
171 $this->msg( 'searchdisabled' )->escaped() .
173 $this->msg( 'googlesearch' )->rawParams(
174 htmlspecialchars( $term ),
176 $this->msg( 'searchbutton' )->escaped()
185 $this->showResults( $term );
189 * Set up basic search parameters from the request and user settings.
191 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
193 public function load() {
194 $request = $this->getRequest();
195 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
196 $this->mPrefix
= $request->getVal( 'prefix', '' );
197 if ( $this->mPrefix
!== '' ) {
198 $this->setExtraParam( 'prefix', $this->mPrefix
);
201 $user = $this->getUser();
203 # Extract manually requested namespaces
204 $nslist = $this->powerSearch( $request );
205 if ( !count( $nslist ) ) {
206 # Fallback to user preference
207 $nslist = $this->searchConfig
->userNamespaces( $user );
211 if ( !count( $nslist ) ) {
212 $profile = 'default';
215 $profile = $request->getVal( 'profile', $profile );
216 $profiles = $this->getSearchProfiles();
217 if ( $profile === null ) {
218 // BC with old request format
219 $profile = 'advanced';
220 foreach ( $profiles as $key => $data ) {
221 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
225 $this->namespaces
= $nslist;
226 } elseif ( $profile === 'advanced' ) {
227 $this->namespaces
= $nslist;
229 if ( isset( $profiles[$profile]['namespaces'] ) ) {
230 $this->namespaces
= $profiles[$profile]['namespaces'];
232 // Unknown profile requested
233 $profile = 'default';
234 $this->namespaces
= $profiles['default']['namespaces'];
238 $this->fulltext
= $request->getVal( 'fulltext' );
239 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
240 $this->profile
= $profile;
244 * If an exact title match can be found, jump straight ahead to it.
246 * @param string $term
247 * @return string|null The url to redirect to, or null if no redirect.
249 public function goResult( $term ) {
250 # If the string cannot be used to create a title
251 if ( is_null( Title
::newFromText( $term ) ) ) {
254 # If there's an exact or very near match, jump right there.
255 $title = $this->getSearchEngine()
256 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
257 if ( is_null( $title ) ) {
261 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
265 return $url ??
$title->getFullUrlForRedirect();
269 * @param string $term
271 public function showResults( $term ) {
272 if ( $this->searchEngineType
!== null ) {
273 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
276 $out = $this->getOutput();
277 $formWidget = new MediaWiki\Widget\Search\
SearchFormWidget(
280 $this->getSearchProfiles()
282 $filePrefix = MediaWikiServices
::getInstance()->getContentLanguage()->
283 getFormattedNsText( NS_FILE
) . ':';
284 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
285 // Empty query -- straight view of search form
286 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
287 # Hook requested termination
291 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
292 // only do the form render here for the empty $term case. Rendering
293 // the form when a search is provided is repeated below.
294 $out->addHTML( $formWidget->render(
295 $this->profile
, $term, 0, 0, $this->offset
, $this->isPowerSearch()
300 $search = $this->getSearchEngine();
301 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
302 $search->setLimitOffset( $this->limit
, $this->offset
);
303 $search->setNamespaces( $this->namespaces
);
304 $search->prefix
= $this->mPrefix
;
306 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
307 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
308 # Hook requested termination
312 $title = Title
::newFromText( $term );
313 $showSuggestion = $title === null ||
!$title->isKnown();
314 $search->setShowSuggestion( $showSuggestion );
316 $rewritten = $search->transformSearchTerm( $term );
317 if ( $rewritten !== $term ) {
319 wfDeprecated( 'SearchEngine::transformSearchTerm() (overridden by ' .
320 get_class( $search ) . ')', '1.32' );
323 $rewritten = $search->replacePrefixes( $term );
324 if ( $rewritten !== $term ) {
325 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
326 get_class( $search ) . ')', '1.32' );
329 // fetch search results
330 $titleMatches = $search->searchTitle( $rewritten );
331 $textMatches = $search->searchText( $rewritten );
334 if ( $textMatches instanceof Status
) {
335 $textStatus = $textMatches;
336 $textMatches = $textStatus->getValue();
339 // Get number of results
340 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
341 if ( $titleMatches ) {
342 $titleMatchesNum = $titleMatches->numRows();
343 $numTitleMatches = $titleMatches->getTotalHits();
345 if ( $textMatches ) {
346 $textMatchesNum = $textMatches->numRows();
347 $numTextMatches = $textMatches->getTotalHits();
348 if ( $textMatchesNum > 0 ) {
349 $search->augmentSearchResults( $textMatches );
352 $num = $titleMatchesNum +
$textMatchesNum;
353 $totalRes = $numTitleMatches +
$numTextMatches;
355 // start rendering the page
357 $out->addHTML( $formWidget->render(
358 $this->profile
, $term, $num, $totalRes, $this->offset
, $this->isPowerSearch()
361 // did you mean... suggestions
362 if ( $textMatches ) {
363 $dymWidget = new MediaWiki\Widget\Search\
DidYouMeanWidget( $this );
364 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
367 $hasErrors = $textStatus && $textStatus->getErrors() !== [];
368 $hasOtherResults = $textMatches &&
369 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
371 if ( $textMatches && $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
372 $out->addHTML( '<div class="searchresults mw-searchresults-has-iw">' );
374 $out->addHTML( '<div class="searchresults">' );
378 list( $error, $warning ) = $textStatus->splitByErrorType();
379 if ( $error->getErrors() ) {
380 $out->addHTML( Html
::errorBox(
381 $error->getHTML( 'search-error' )
384 if ( $warning->getErrors() ) {
385 $out->addHTML( Html
::warningBox(
386 $warning->getHTML( 'search-warning' )
391 // Show the create link ahead
392 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
394 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
396 // If we have no results and have not already displayed an error message
397 if ( $num === 0 && !$hasErrors ) {
398 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
399 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
400 wfEscapeWikiText( $term )
404 // Although $num might be 0 there can still be secondary or inline
405 // results to display.
406 $linkRenderer = $this->getLinkRenderer();
407 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
409 // Default (null) on. Can be explicitly disabled.
410 if ( $search->getFeatureData( 'enable-new-crossproject-page' ) !== false ) {
411 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
412 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
414 $sidebarResultWidget,
416 MediaWikiServices
::getInstance()->getInterwikiLookup(),
417 $search->getFeatureData( 'show-multimedia-search-results' )
420 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
421 $sidebarResultsWidget = new SimpleSearchResultSetWidget(
423 $sidebarResultWidget,
425 MediaWikiServices
::getInstance()->getInterwikiLookup()
429 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
431 $out->addHTML( $widget->render(
432 $term, $this->offset
, $titleMatches, $textMatches
435 if ( $titleMatches ) {
436 $titleMatches->free();
439 if ( $textMatches ) {
440 $textMatches->free();
443 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
446 if ( $totalRes > $this->limit ||
$this->offset
) {
447 // Allow matches to define the correct offset, as interleaved
448 // AB testing may require a different next page offset.
449 if ( $textMatches && $textMatches->getOffset() !== null ) {
450 $offset = $textMatches->getOffset();
452 $offset = $this->offset
;
455 $prevnext = $this->getLanguage()->viewPrevNext(
456 $this->getPageTitle(),
459 $this->powerSearchOptions() +
[ 'search' => $term ],
460 $this->limit +
$this->offset
>= $totalRes
462 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
465 // Close <div class='searchresults'>
466 $out->addHTML( "</div>" );
468 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
472 * @param Title $title
473 * @param int $num The number of search results found
474 * @param null|SearchResultSet $titleMatches Results from title search
475 * @param null|SearchResultSet $textMatches Results from text search
477 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
478 // show direct page/create link if applicable
480 // Check DBkey !== '' in case of fragment link only.
481 if ( is_null( $title ) ||
$title->getDBkey() === ''
482 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
483 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
486 // preserve the paragraph for margins etc...
487 $this->getOutput()->addHTML( '<p></p>' );
492 $messageName = 'searchmenu-new-nocreate';
493 $linkClass = 'mw-search-createlink';
495 if ( !$title->isExternal() ) {
496 if ( $title->isKnown() ) {
497 $messageName = 'searchmenu-exists';
498 $linkClass = 'mw-search-exists';
499 } elseif ( ContentHandler
::getForTitle( $title )->supportsDirectEditing()
500 && $title->quickUserCan( 'create', $this->getUser() )
502 $messageName = 'searchmenu-new';
508 wfEscapeWikiText( $title->getPrefixedText() ),
509 Message
::numParam( $num )
511 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
513 // Extensions using the hook might still return an empty $messageName
514 if ( $messageName ) {
515 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
517 // preserve the paragraph for margins etc...
518 $this->getOutput()->addHTML( '<p></p>' );
523 * Sets up everything for the HTML output page including styles, javascript,
526 * @param string $term
528 protected function setupPage( $term ) {
529 $out = $this->getOutput();
532 $this->outputHeader();
533 // TODO: Is this true? The namespace remember uses a user token
535 $out->allowClickjacking();
536 $this->addHelpLink( 'Help:Searching' );
538 if ( strval( $term ) !== '' ) {
539 $out->setPageTitle( $this->msg( 'searchresults' ) );
540 $out->setHTMLTitle( $this->msg( 'pagetitle' )
541 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
542 ->inContentLanguage()->text()
546 if ( $this->mPrefix
!== '' ) {
547 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix
);
548 $params = $this->powerSearchOptions();
549 unset( $params['prefix'] );
556 $subtitle .= Xml
::element(
559 'href' => $this->getPageTitle()->getLocalURL( $params ),
560 'title' => $this->msg( 'search-filter-title-prefix-reset' ),
562 $this->msg( 'search-filter-title-prefix-reset' )
565 $out->setSubtitle( $subtitle );
568 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
569 $out->addModules( 'mediawiki.special.search' );
570 $out->addModuleStyles( [
571 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
572 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
577 * Return true if current search is a power (advanced) search
581 protected function isPowerSearch() {
582 return $this->profile
=== 'advanced';
586 * Extract "power search" namespace settings from the request object,
587 * returning a list of index numbers to search.
589 * @param WebRequest &$request
592 protected function powerSearch( &$request ) {
594 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
595 if ( $request->getCheck( 'ns' . $ns ) ) {
604 * Reconstruct the 'power search' options for links
605 * TODO: Instead of exposing this publicly, could we instead expose
606 * a function for creating search links?
610 public function powerSearchOptions() {
612 if ( $this->isPowerSearch() ) {
613 foreach ( $this->namespaces
as $n ) {
617 $opt['profile'] = $this->profile
;
620 return $opt +
$this->extraParams
;
624 * Save namespace preferences when we're supposed to
626 * @return bool Whether we wrote something
628 protected function saveNamespaces() {
629 $user = $this->getUser();
630 $request = $this->getRequest();
632 if ( $user->isLoggedIn() &&
633 $user->matchEditToken(
634 $request->getVal( 'nsRemember' ),
639 // Reset namespace preferences: namespaces are not searched
640 // when they're not mentioned in the URL parameters.
641 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
642 $user->setOption( 'searchNs' . $n, false );
644 // The request parameters include all the namespaces to be searched.
645 // Even if they're the same as an existing profile, they're not eaten.
646 foreach ( $this->namespaces
as $n ) {
647 $user->setOption( 'searchNs' . $n, true );
650 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
651 $user->saveSettings();
663 protected function getSearchProfiles() {
664 // Builds list of Search Types (profiles)
665 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
666 $defaultNs = $this->searchConfig
->defaultNamespaces();
669 'message' => 'searchprofile-articles',
670 'tooltip' => 'searchprofile-articles-tooltip',
671 'namespaces' => $defaultNs,
672 'namespace-messages' => $this->searchConfig
->namespacesAsText(
677 'message' => 'searchprofile-images',
678 'tooltip' => 'searchprofile-images-tooltip',
679 'namespaces' => [ NS_FILE
],
682 'message' => 'searchprofile-everything',
683 'tooltip' => 'searchprofile-everything-tooltip',
684 'namespaces' => $nsAllSet,
687 'message' => 'searchprofile-advanced',
688 'tooltip' => 'searchprofile-advanced-tooltip',
689 'namespaces' => self
::NAMESPACES_CURRENT
,
693 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
695 foreach ( $profiles as &$data ) {
696 if ( !is_array( $data['namespaces'] ) ) {
699 sort( $data['namespaces'] );
708 * @return SearchEngine
710 public function getSearchEngine() {
711 if ( $this->searchEngine
=== null ) {
712 $this->searchEngine
= $this->searchEngineType ?
713 MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType
) :
714 MediaWikiServices
::getInstance()->newSearchEngine();
717 return $this->searchEngine
;
721 * Current search profile.
722 * @return null|string
724 function getProfile() {
725 return $this->profile
;
729 * Current namespaces.
732 function getNamespaces() {
733 return $this->namespaces
;
737 * Users of hook SpecialSearchSetupEngine can use this to
738 * add more params to links to not lose selection when
739 * user navigates search results.
743 * @param mixed $value
745 public function setExtraParam( $key, $value ) {
746 $this->extraParams
[$key] = $value;
750 * The prefix value send to Special:Search using the 'prefix' URI param
751 * It means that the user is willing to search for pages whose titles start with
753 * (Used by the InputBox extension)
757 public function getPrefix() {
758 return $this->mPrefix
;
761 protected function getGroupName() {