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();
105 * @param string|null $par
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 ( $par !== null && $par !== '' && $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 ( $request->getCheck( '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' );
144 if ( !$request->getVal( 'fulltext' ) && !$request->getCheck( 'offset' ) ) {
145 $url = $this->goResult( $term );
146 if ( $url !== null ) {
148 $out->redirect( $url );
151 // No match. If it could plausibly be a title
152 // run the No go match hook.
153 $title = Title
::newFromText( $term );
154 if ( !is_null( $title ) ) {
155 Hooks
::run( 'SpecialSearchNogomatch', [ &$title ] );
159 $this->setupPage( $term );
161 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
162 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
163 if ( $searchForwardUrl ) {
164 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
165 $out->redirect( $url );
167 $this->showGoogleSearch( $term );
173 $this->showResults( $term );
177 * Output a google search form if search is disabled
179 * @param string $term Search term
180 * @todo FIXME Maybe we should get rid of this raw html message at some future time
181 * @suppress SecurityCheck-XSS
183 private function showGoogleSearch( $term ) {
184 $this->getOutput()->addHTML(
187 $this->msg( 'search-external' )->escaped() .
189 "<p class='mw-searchdisabled'>" .
190 $this->msg( 'searchdisabled' )->escaped() .
192 $this->msg( 'googlesearch' )->rawParams(
193 htmlspecialchars( $term ),
195 $this->msg( 'searchbutton' )->escaped()
202 * Set up basic search parameters from the request and user settings.
204 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
206 public function load() {
207 $request = $this->getRequest();
208 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
209 $this->mPrefix
= $request->getVal( 'prefix', '' );
210 if ( $this->mPrefix
!== '' ) {
211 $this->setExtraParam( 'prefix', $this->mPrefix
);
214 $this->sort
= $request->getVal( 'sort', SearchEngine
::DEFAULT_SORT
);
215 if ( $this->sort
!== SearchEngine
::DEFAULT_SORT
) {
216 $this->setExtraParam( 'sort', $this->sort
);
219 $user = $this->getUser();
221 # Extract manually requested namespaces
222 $nslist = $this->powerSearch( $request );
223 if ( $nslist === [] ) {
224 # Fallback to user preference
225 $nslist = $this->searchConfig
->userNamespaces( $user );
229 if ( $nslist === [] ) {
230 $profile = 'default';
233 $profile = $request->getVal( 'profile', $profile );
234 $profiles = $this->getSearchProfiles();
235 if ( $profile === null ) {
236 // BC with old request format
237 $profile = 'advanced';
238 foreach ( $profiles as $key => $data ) {
239 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
243 $this->namespaces
= $nslist;
244 } elseif ( $profile === 'advanced' ) {
245 $this->namespaces
= $nslist;
246 } elseif ( isset( $profiles[$profile]['namespaces'] ) ) {
247 $this->namespaces
= $profiles[$profile]['namespaces'];
249 // Unknown profile requested
250 $profile = 'default';
251 $this->namespaces
= $profiles['default']['namespaces'];
254 $this->fulltext
= $request->getVal( 'fulltext' );
255 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
256 $this->profile
= $profile;
260 * If an exact title match can be found, jump straight ahead to it.
262 * @param string $term
263 * @return string|null The url to redirect to, or null if no redirect.
265 public function goResult( $term ) {
266 # If the string cannot be used to create a title
267 if ( is_null( Title
::newFromText( $term ) ) ) {
270 # If there's an exact or very near match, jump right there.
271 $title = $this->getSearchEngine()
272 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
273 if ( is_null( $title ) ) {
277 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
281 return $url ??
$title->getFullUrlForRedirect();
285 * @param string $term
287 public function showResults( $term ) {
288 if ( $this->searchEngineType
!== null ) {
289 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
292 $out = $this->getOutput();
293 $formWidget = new MediaWiki\Widget\Search\
SearchFormWidget(
296 $this->getSearchProfiles()
298 $filePrefix = MediaWikiServices
::getInstance()->getContentLanguage()->
299 getFormattedNsText( NS_FILE
) . ':';
300 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
301 // Empty query -- straight view of search form
302 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
303 # Hook requested termination
307 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
308 // only do the form render here for the empty $term case. Rendering
309 // the form when a search is provided is repeated below.
310 $out->addHTML( $formWidget->render(
311 $this->profile
, $term, 0, 0, $this->offset
, $this->isPowerSearch()
316 $search = $this->getSearchEngine();
317 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
318 $search->setLimitOffset( $this->limit
, $this->offset
);
319 $search->setNamespaces( $this->namespaces
);
320 $search->setSort( $this->sort
);
321 $search->prefix
= $this->mPrefix
;
323 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
324 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
325 # Hook requested termination
329 $title = Title
::newFromText( $term );
330 $showSuggestion = $title === null ||
!$title->isKnown();
331 $search->setShowSuggestion( $showSuggestion );
333 $rewritten = $search->replacePrefixes( $term );
334 if ( $rewritten !== $term ) {
335 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
336 get_class( $search ) . ')', '1.32' );
339 // fetch search results
340 $titleMatches = $search->searchTitle( $rewritten );
341 $textMatches = $search->searchText( $rewritten );
344 if ( $textMatches instanceof Status
) {
345 $textStatus = $textMatches;
346 $textMatches = $textStatus->getValue();
349 // Get number of results
350 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
351 if ( $titleMatches ) {
352 $titleMatchesNum = $titleMatches->numRows();
353 $numTitleMatches = $titleMatches->getTotalHits();
355 if ( $textMatches ) {
356 $textMatchesNum = $textMatches->numRows();
357 $numTextMatches = $textMatches->getTotalHits();
358 if ( $textMatchesNum > 0 ) {
359 $search->augmentSearchResults( $textMatches );
362 $num = $titleMatchesNum +
$textMatchesNum;
363 $totalRes = $numTitleMatches +
$numTextMatches;
365 // start rendering the page
367 $out->addHTML( $formWidget->render(
368 $this->profile
, $term, $num, $totalRes, $this->offset
, $this->isPowerSearch()
371 // did you mean... suggestions
372 if ( $textMatches ) {
373 $dymWidget = new MediaWiki\Widget\Search\
DidYouMeanWidget( $this );
374 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
377 $hasErrors = $textStatus && $textStatus->getErrors() !== [];
378 $hasOtherResults = $textMatches &&
379 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
381 if ( $textMatches && $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
382 $out->addHTML( '<div class="searchresults mw-searchresults-has-iw">' );
384 $out->addHTML( '<div class="searchresults">' );
388 list( $error, $warning ) = $textStatus->splitByErrorType();
389 if ( $error->getErrors() ) {
390 $out->addHTML( Html
::errorBox(
391 $error->getHTML( 'search-error' )
394 if ( $warning->getErrors() ) {
395 $out->addHTML( Html
::warningBox(
396 $warning->getHTML( 'search-warning' )
401 // Show the create link ahead
402 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
404 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
406 // If we have no results and have not already displayed an error message
407 if ( $num === 0 && !$hasErrors ) {
408 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
409 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
410 wfEscapeWikiText( $term )
414 // Although $num might be 0 there can still be secondary or inline
415 // results to display.
416 $linkRenderer = $this->getLinkRenderer();
417 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
419 // Default (null) on. Can be explicitly disabled.
420 if ( $search->getFeatureData( 'enable-new-crossproject-page' ) !== false ) {
421 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
422 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
424 $sidebarResultWidget,
426 MediaWikiServices
::getInstance()->getInterwikiLookup(),
427 $search->getFeatureData( 'show-multimedia-search-results' )
430 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
431 $sidebarResultsWidget = new SimpleSearchResultSetWidget(
433 $sidebarResultWidget,
435 MediaWikiServices
::getInstance()->getInterwikiLookup()
439 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
441 $out->addHTML( $widget->render(
442 $term, $this->offset
, $titleMatches, $textMatches
445 if ( $titleMatches ) {
446 $titleMatches->free();
449 if ( $textMatches ) {
450 $textMatches->free();
453 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
456 if ( $totalRes > $this->limit ||
$this->offset
) {
457 // Allow matches to define the correct offset, as interleaved
458 // AB testing may require a different next page offset.
459 if ( $textMatches && $textMatches->getOffset() !== null ) {
460 $offset = $textMatches->getOffset();
462 $offset = $this->offset
;
465 $prevnext = $this->buildPrevNextNavigation(
468 $this->powerSearchOptions() +
[ 'search' => $term ],
469 $this->limit +
$this->offset
>= $totalRes
471 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
474 // Close <div class='searchresults'>
475 $out->addHTML( "</div>" );
477 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
481 * @param Title $title
482 * @param int $num The number of search results found
483 * @param null|SearchResultSet $titleMatches Results from title search
484 * @param null|SearchResultSet $textMatches Results from text search
486 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
487 // show direct page/create link if applicable
489 // Check DBkey !== '' in case of fragment link only.
490 if ( is_null( $title ) ||
$title->getDBkey() === ''
491 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
492 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
495 // preserve the paragraph for margins etc...
496 $this->getOutput()->addHTML( '<p></p>' );
501 $messageName = 'searchmenu-new-nocreate';
502 $linkClass = 'mw-search-createlink';
504 if ( !$title->isExternal() ) {
505 if ( $title->isKnown() ) {
506 $messageName = 'searchmenu-exists';
507 $linkClass = 'mw-search-exists';
508 } elseif ( ContentHandler
::getForTitle( $title )->supportsDirectEditing()
509 && $title->quickUserCan( 'create', $this->getUser() )
511 $messageName = 'searchmenu-new';
517 wfEscapeWikiText( $title->getPrefixedText() ),
518 Message
::numParam( $num )
520 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
522 // Extensions using the hook might still return an empty $messageName
523 if ( $messageName ) {
524 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
526 // preserve the paragraph for margins etc...
527 $this->getOutput()->addHTML( '<p></p>' );
532 * Sets up everything for the HTML output page including styles, javascript,
535 * @param string $term
537 protected function setupPage( $term ) {
538 $out = $this->getOutput();
541 $this->outputHeader();
542 // TODO: Is this true? The namespace remember uses a user token
544 $out->allowClickjacking();
545 $this->addHelpLink( 'Help:Searching' );
547 if ( strval( $term ) !== '' ) {
548 $out->setPageTitle( $this->msg( 'searchresults' ) );
549 $out->setHTMLTitle( $this->msg( 'pagetitle' )
550 ->plaintextParams( $this->msg( 'searchresults-title' )->plaintextParams( $term )->text() )
551 ->inContentLanguage()->text()
555 if ( $this->mPrefix
!== '' ) {
556 $subtitle = $this->msg( 'search-filter-title-prefix' )->plaintextParams( $this->mPrefix
);
557 $params = $this->powerSearchOptions();
558 unset( $params['prefix'] );
565 $subtitle .= Xml
::element(
568 'href' => $this->getPageTitle()->getLocalURL( $params ),
569 'title' => $this->msg( 'search-filter-title-prefix-reset' )->text(),
571 $this->msg( 'search-filter-title-prefix-reset' )->text()
574 $out->setSubtitle( $subtitle );
577 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
578 $out->addModules( 'mediawiki.special.search' );
579 $out->addModuleStyles( [
580 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
581 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
586 * Return true if current search is a power (advanced) search
590 protected function isPowerSearch() {
591 return $this->profile
=== 'advanced';
595 * Extract "power search" namespace settings from the request object,
596 * returning a list of index numbers to search.
598 * @param WebRequest &$request
601 protected function powerSearch( &$request ) {
603 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
604 if ( $request->getCheck( 'ns' . $ns ) ) {
613 * Reconstruct the 'power search' options for links
614 * TODO: Instead of exposing this publicly, could we instead expose
615 * a function for creating search links?
619 public function powerSearchOptions() {
621 if ( $this->isPowerSearch() ) {
622 foreach ( $this->namespaces
as $n ) {
626 $opt['profile'] = $this->profile
;
629 return $opt +
$this->extraParams
;
633 * Save namespace preferences when we're supposed to
635 * @return bool Whether we wrote something
637 protected function saveNamespaces() {
638 $user = $this->getUser();
639 $request = $this->getRequest();
641 if ( $user->isLoggedIn() &&
642 $user->matchEditToken(
643 $request->getVal( 'nsRemember' ),
648 // Reset namespace preferences: namespaces are not searched
649 // when they're not mentioned in the URL parameters.
650 foreach ( MediaWikiServices
::getInstance()->getNamespaceInfo()->getValidNamespaces()
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() {