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', '' );
198 $user = $this->getUser();
200 # Extract manually requested namespaces
201 $nslist = $this->powerSearch( $request );
202 if ( !count( $nslist ) ) {
203 # Fallback to user preference
204 $nslist = $this->searchConfig
->userNamespaces( $user );
208 if ( !count( $nslist ) ) {
209 $profile = 'default';
212 $profile = $request->getVal( 'profile', $profile );
213 $profiles = $this->getSearchProfiles();
214 if ( $profile === null ) {
215 // BC with old request format
216 $profile = 'advanced';
217 foreach ( $profiles as $key => $data ) {
218 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
222 $this->namespaces
= $nslist;
223 } elseif ( $profile === 'advanced' ) {
224 $this->namespaces
= $nslist;
226 if ( isset( $profiles[$profile]['namespaces'] ) ) {
227 $this->namespaces
= $profiles[$profile]['namespaces'];
229 // Unknown profile requested
230 $profile = 'default';
231 $this->namespaces
= $profiles['default']['namespaces'];
235 $this->fulltext
= $request->getVal( 'fulltext' );
236 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
237 $this->profile
= $profile;
241 * If an exact title match can be found, jump straight ahead to it.
243 * @param string $term
244 * @return string|null The url to redirect to, or null if no redirect.
246 public function goResult( $term ) {
247 # If the string cannot be used to create a title
248 if ( is_null( Title
::newFromText( $term ) ) ) {
251 # If there's an exact or very near match, jump right there.
252 $title = $this->getSearchEngine()
253 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
254 if ( is_null( $title ) ) {
258 if ( !Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
262 return $url === null ?
$title->getFullURL() : $url;
266 * @param string $term
268 public function showResults( $term ) {
271 if ( $this->searchEngineType
!== null ) {
272 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
275 $out = $this->getOutput();
276 $formWidget = new MediaWiki\Widget\Search\
SearchFormWidget(
279 $this->getSearchProfiles()
281 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
282 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
283 // Empty query -- straight view of search form
284 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
285 # Hook requested termination
289 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
290 // only do the form render here for the empty $term case. Rendering
291 // the form when a search is provided is repeated below.
292 $out->addHTML( $formWidget->render(
293 $this->profile
, $term, 0, 0, $this->offset
, $this->isPowerSearch()
298 $search = $this->getSearchEngine();
299 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
300 $search->setLimitOffset( $this->limit
, $this->offset
);
301 $search->setNamespaces( $this->namespaces
);
302 $search->prefix
= $this->mPrefix
;
303 $term = $search->transformSearchTerm( $term );
305 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
306 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
307 # Hook requested termination
311 $title = Title
::newFromText( $term );
312 $showSuggestion = $title === null ||
!$title->isKnown();
313 $search->setShowSuggestion( $showSuggestion );
315 // fetch search results
316 $rewritten = $search->replacePrefixes( $term );
318 $titleMatches = $search->searchTitle( $rewritten );
319 $textMatches = $search->searchText( $rewritten );
322 if ( $textMatches instanceof Status
) {
323 $textStatus = $textMatches;
324 $textMatches = $textStatus->getValue();
327 // Get number of results
328 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
329 if ( $titleMatches ) {
330 $titleMatchesNum = $titleMatches->numRows();
331 $numTitleMatches = $titleMatches->getTotalHits();
333 if ( $textMatches ) {
334 $textMatchesNum = $textMatches->numRows();
335 $numTextMatches = $textMatches->getTotalHits();
336 if ( $textMatchesNum > 0 ) {
337 $search->augmentSearchResults( $textMatches );
340 $num = $titleMatchesNum +
$textMatchesNum;
341 $totalRes = $numTitleMatches +
$numTextMatches;
343 // start rendering the page
345 $out->addHTML( $formWidget->render(
346 $this->profile
, $term, $num, $totalRes, $this->offset
, $this->isPowerSearch()
349 // did you mean... suggestions
350 if ( $textMatches ) {
351 $dymWidget = new MediaWiki\Widget\Search\
DidYouMeanWidget( $this );
352 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
355 $out->addHTML( "<div class='searchresults'>" );
357 $hasErrors = $textStatus && $textStatus->getErrors();
358 $hasOtherResults = $textMatches &&
359 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
362 list( $error, $warning ) = $textStatus->splitByErrorType();
363 if ( $error->getErrors() ) {
364 $out->addHTML( Html
::rawElement(
366 [ 'class' => 'errorbox' ],
367 $error->getHTML( 'search-error' )
370 if ( $warning->getErrors() ) {
371 $out->addHTML( Html
::rawElement(
373 [ 'class' => 'warningbox' ],
374 $warning->getHTML( 'search-warning' )
379 // Show the create link ahead
380 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
382 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
384 // If we have no results and have not already displayed an error message
385 if ( $num === 0 && !$hasErrors ) {
386 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
387 $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
388 wfEscapeWikiText( $term )
392 // Although $num might be 0 there can still be secondary or inline
393 // results to display.
394 $linkRenderer = $this->getLinkRenderer();
395 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
397 if ( $search->getFeatureData( 'enable-new-crossproject-page' ) ) {
399 $sidebarResultWidget = new InterwikiSearchResultWidget( $this, $linkRenderer );
400 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
402 $sidebarResultWidget,
404 MediaWikiServices
::getInstance()->getInterwikiLookup()
407 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
408 $sidebarResultsWidget = new SimpleSearchResultSetWidget(
410 $sidebarResultWidget,
412 MediaWikiServices
::getInstance()->getInterwikiLookup()
416 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
418 $out->addHTML( $widget->render(
419 $term, $this->offset
, $titleMatches, $textMatches
422 if ( $titleMatches ) {
423 $titleMatches->free();
426 if ( $textMatches ) {
427 $textMatches->free();
430 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
433 if ( $totalRes > $this->limit ||
$this->offset
) {
434 $prevnext = $this->getLanguage()->viewPrevNext(
435 $this->getPageTitle(),
438 $this->powerSearchOptions() +
[ 'search' => $term ],
439 $this->limit +
$this->offset
>= $totalRes
441 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
444 // Close <div class='searchresults'>
445 $out->addHTML( "</div>" );
447 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
451 * @param Title $title
452 * @param int $num The number of search results found
453 * @param null|SearchResultSet $titleMatches Results from title search
454 * @param null|SearchResultSet $textMatches Results from text search
456 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
457 // show direct page/create link if applicable
459 // Check DBkey !== '' in case of fragment link only.
460 if ( is_null( $title ) ||
$title->getDBkey() === ''
461 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
462 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
465 // preserve the paragraph for margins etc...
466 $this->getOutput()->addHTML( '<p></p>' );
471 $messageName = 'searchmenu-new-nocreate';
472 $linkClass = 'mw-search-createlink';
474 if ( !$title->isExternal() ) {
475 if ( $title->isKnown() ) {
476 $messageName = 'searchmenu-exists';
477 $linkClass = 'mw-search-exists';
478 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
479 $messageName = 'searchmenu-new';
485 wfEscapeWikiText( $title->getPrefixedText() ),
486 Message
::numParam( $num )
488 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
490 // Extensions using the hook might still return an empty $messageName
491 if ( $messageName ) {
492 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
494 // preserve the paragraph for margins etc...
495 $this->getOutput()->addHTML( '<p></p>' );
500 * Sets up everything for the HTML output page including styles, javascript,
503 * @param string $term
505 protected function setupPage( $term ) {
506 $out = $this->getOutput();
509 $this->outputHeader();
510 // TODO: Is this true? The namespace remember uses a user token
512 $out->allowClickjacking();
513 $this->addHelpLink( 'Help:Searching' );
515 if ( strval( $term ) !== '' ) {
516 $out->setPageTitle( $this->msg( 'searchresults' ) );
517 $out->setHTMLTitle( $this->msg( 'pagetitle' )
518 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
519 ->inContentLanguage()->text()
523 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
524 $out->addModules( 'mediawiki.special.search' );
525 $out->addModuleStyles( [
526 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
527 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
532 * Return true if current search is a power (advanced) search
536 protected function isPowerSearch() {
537 return $this->profile
=== 'advanced';
541 * Extract "power search" namespace settings from the request object,
542 * returning a list of index numbers to search.
544 * @param WebRequest $request
547 protected function powerSearch( &$request ) {
549 foreach ( $this->searchConfig
->searchableNamespaces() as $ns => $name ) {
550 if ( $request->getCheck( 'ns' . $ns ) ) {
559 * Reconstruct the 'power search' options for links
560 * TODO: Instead of exposing this publicly, could we instead expose
561 * a function for creating search links?
565 public function powerSearchOptions() {
567 if ( $this->isPowerSearch() ) {
568 foreach ( $this->namespaces
as $n ) {
572 $opt['profile'] = $this->profile
;
575 return $opt +
$this->extraParams
;
579 * Save namespace preferences when we're supposed to
581 * @return bool Whether we wrote something
583 protected function saveNamespaces() {
584 $user = $this->getUser();
585 $request = $this->getRequest();
587 if ( $user->isLoggedIn() &&
588 $user->matchEditToken(
589 $request->getVal( 'nsRemember' ),
594 // Reset namespace preferences: namespaces are not searched
595 // when they're not mentioned in the URL parameters.
596 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
597 $user->setOption( 'searchNs' . $n, false );
599 // The request parameters include all the namespaces to be searched.
600 // Even if they're the same as an existing profile, they're not eaten.
601 foreach ( $this->namespaces
as $n ) {
602 $user->setOption( 'searchNs' . $n, true );
605 DeferredUpdates
::addCallableUpdate( function () use ( $user ) {
606 $user->saveSettings();
618 protected function getSearchProfiles() {
619 // Builds list of Search Types (profiles)
620 $nsAllSet = array_keys( $this->searchConfig
->searchableNamespaces() );
621 $defaultNs = $this->searchConfig
->defaultNamespaces();
624 'message' => 'searchprofile-articles',
625 'tooltip' => 'searchprofile-articles-tooltip',
626 'namespaces' => $defaultNs,
627 'namespace-messages' => $this->searchConfig
->namespacesAsText(
632 'message' => 'searchprofile-images',
633 'tooltip' => 'searchprofile-images-tooltip',
634 'namespaces' => [ NS_FILE
],
637 'message' => 'searchprofile-everything',
638 'tooltip' => 'searchprofile-everything-tooltip',
639 'namespaces' => $nsAllSet,
642 'message' => 'searchprofile-advanced',
643 'tooltip' => 'searchprofile-advanced-tooltip',
644 'namespaces' => self
::NAMESPACES_CURRENT
,
648 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
650 foreach ( $profiles as &$data ) {
651 if ( !is_array( $data['namespaces'] ) ) {
654 sort( $data['namespaces'] );
663 * @return SearchEngine
665 public function getSearchEngine() {
666 if ( $this->searchEngine
=== null ) {
667 $this->searchEngine
= $this->searchEngineType ?
668 MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType
) :
669 MediaWikiServices
::getInstance()->newSearchEngine();
672 return $this->searchEngine
;
676 * Current search profile.
677 * @return null|string
679 function getProfile() {
680 return $this->profile
;
684 * Current namespaces.
687 function getNamespaces() {
688 return $this->namespaces
;
692 * Users of hook SpecialSearchSetupEngine can use this to
693 * add more params to links to not lose selection when
694 * user navigates search results.
698 * @param mixed $value
700 public function setExtraParam( $key, $value ) {
701 $this->extraParams
[$key] = $value;
704 protected function getGroupName() {