Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / specials / SpecialSearch.php
blob34620ff9e20b9ec155c614c3a51298812278c867
1 <?php
2 /**
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
22 * @file
23 * @ingroup SpecialPage
26 use MediaWiki\MediaWikiServices;
27 use MediaWiki\Widget\Search\BasicSearchResultSetWidget;
28 use MediaWiki\Widget\Search\InterwikiSearchResultSetWidget;
29 use MediaWiki\Widget\Search\FullSearchResultWidget;
30 use MediaWiki\Widget\Search\SimpleSearchResultWidget;
32 /**
33 * implements Special:Search - Run text & title search and display the output
34 * @ingroup SpecialPage
36 class SpecialSearch extends SpecialPage {
37 /**
38 * Current search profile. Search profile is just a name that identifies
39 * the active search tab on the search page (content, discussions...)
40 * For users tt replaces the set of enabled namespaces from the query
41 * string when applicable. Extensions can add new profiles with hooks
42 * with custom search options just for that profile.
43 * @var null|string
45 protected $profile;
47 /** @var SearchEngine Search engine */
48 protected $searchEngine;
50 /** @var string Search engine type, if not default */
51 protected $searchEngineType;
53 /** @var array For links */
54 protected $extraParams = [];
56 /**
57 * @var string The prefix url parameter. Set on the searcher and the
58 * is expected to treat it as prefix filter on titles.
60 protected $mPrefix;
62 /**
63 * @var int
65 protected $limit, $offset;
67 /**
68 * @var array
70 protected $namespaces;
72 /**
73 * @var string
75 protected $fulltext;
77 /**
78 * @var bool
80 protected $runSuggestion = true;
82 /**
83 * Search engine configurations.
84 * @var SearchEngineConfig
86 protected $searchConfig;
88 const NAMESPACES_CURRENT = 'sense';
90 public function __construct() {
91 parent::__construct( 'Search' );
92 $this->searchConfig = MediaWikiServices::getInstance()->getSearchEngineConfig();
95 /**
96 * Entry point
98 * @param string $par
100 public function execute( $par ) {
101 $request = $this->getRequest();
102 $out = $this->getOutput();
104 // Fetch the search term
105 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
107 // Historically search terms have been accepted not only in the search query
108 // parameter, but also as part of the primary url. This can have PII implications
109 // in releasing page view data. As such issue a 301 redirect to the correct
110 // URL.
111 if ( strlen( $par ) && !strlen( $term ) ) {
112 $query = $request->getValues();
113 unset( $query['title'] );
114 // Strip underscores from title parameter; most of the time we'll want
115 // text form here. But don't strip underscores from actual text params!
116 $query['search'] = str_replace( '_', ' ', $par );
117 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
118 return;
121 // Need to load selected namespaces before handling nsRemember
122 $this->load();
123 // TODO: This performs database actions on GET request, which is going to
124 // be a problem for our multi-datacenter work.
125 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
126 $this->saveNamespaces();
127 // Remove the token from the URL to prevent the user from inadvertently
128 // exposing it (e.g. by pasting it into a public wiki page) or undoing
129 // later settings changes (e.g. by reloading the page).
130 $query = $request->getValues();
131 unset( $query['title'], $query['nsRemember'] );
132 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
133 return;
136 $this->searchEngineType = $request->getVal( 'srbackend' );
137 if (
138 !$request->getVal( 'fulltext' ) &&
139 $request->getVal( 'offset' ) === null
141 $url = $this->goResult( $term );
142 if ( $url !== null ) {
143 // successful 'go'
144 $out->redirect( $url );
145 return;
149 $this->setupPage( $term );
151 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
152 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
153 if ( $searchForwardUrl ) {
154 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
155 $out->redirect( $url );
156 } else {
157 $out->addHTML(
158 "<fieldset>" .
159 "<legend>" .
160 $this->msg( 'search-external' )->escaped() .
161 "</legend>" .
162 "<p class='mw-searchdisabled'>" .
163 $this->msg( 'searchdisabled' )->escaped() .
164 "</p>" .
165 $this->msg( 'googlesearch' )->rawParams(
166 htmlspecialchars( $term ),
167 'UTF-8',
168 $this->msg( 'searchbutton' )->escaped()
169 )->text() .
170 "</fieldset>"
174 return;
177 $this->showResults( $term );
181 * Set up basic search parameters from the request and user settings.
183 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
185 public function load() {
186 $request = $this->getRequest();
187 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
188 $this->mPrefix = $request->getVal( 'prefix', '' );
190 $user = $this->getUser();
192 # Extract manually requested namespaces
193 $nslist = $this->powerSearch( $request );
194 if ( !count( $nslist ) ) {
195 # Fallback to user preference
196 $nslist = $this->searchConfig->userNamespaces( $user );
199 $profile = null;
200 if ( !count( $nslist ) ) {
201 $profile = 'default';
204 $profile = $request->getVal( 'profile', $profile );
205 $profiles = $this->getSearchProfiles();
206 if ( $profile === null ) {
207 // BC with old request format
208 $profile = 'advanced';
209 foreach ( $profiles as $key => $data ) {
210 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
211 $profile = $key;
214 $this->namespaces = $nslist;
215 } elseif ( $profile === 'advanced' ) {
216 $this->namespaces = $nslist;
217 } else {
218 if ( isset( $profiles[$profile]['namespaces'] ) ) {
219 $this->namespaces = $profiles[$profile]['namespaces'];
220 } else {
221 // Unknown profile requested
222 $profile = 'default';
223 $this->namespaces = $profiles['default']['namespaces'];
227 $this->fulltext = $request->getVal( 'fulltext' );
228 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
229 $this->profile = $profile;
233 * If an exact title match can be found, jump straight ahead to it.
235 * @param string $term
236 * @return string|null The url to redirect to, or null if no redirect.
238 public function goResult( $term ) {
239 # If the string cannot be used to create a title
240 if ( is_null( Title::newFromText( $term ) ) ) {
241 return null;
243 # If there's an exact or very near match, jump right there.
244 $title = $this->getSearchEngine()
245 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
246 if ( is_null( $title ) ) {
247 return null;
249 $url = null;
250 if ( !Hooks::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
251 return null;
254 return $url === null ? $title->getFullURL() : $url;
258 * @param string $term
260 public function showResults( $term ) {
261 global $wgContLang;
263 if ( $this->searchEngineType !== null ) {
264 $this->setExtraParam( 'srbackend', $this->searchEngineType );
267 $out = $this->getOutput();
268 $formWidget = new MediaWiki\Widget\Search\SearchFormWidget(
269 $this,
270 $this->searchConfig,
271 $this->getSearchProfiles()
273 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
274 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
275 // Empty query -- straight view of search form
276 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
277 # Hook requested termination
278 return;
280 $out->enableOOUI();
281 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
282 // only do the form render here for the empty $term case. Rendering
283 // the form when a search is provided is repeated below.
284 $out->addHTML( $formWidget->render(
285 $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch()
286 ) );
287 return;
290 $search = $this->getSearchEngine();
291 $search->setFeatureData( 'rewrite', $this->runSuggestion );
292 $search->setLimitOffset( $this->limit, $this->offset );
293 $search->setNamespaces( $this->namespaces );
294 $search->prefix = $this->mPrefix;
295 $term = $search->transformSearchTerm( $term );
297 Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
298 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
299 # Hook requested termination
300 return;
303 $title = Title::newFromText( $term );
304 $showSuggestion = $title === null || !$title->isKnown();
305 $search->setShowSuggestion( $showSuggestion );
307 // fetch search results
308 $rewritten = $search->replacePrefixes( $term );
310 $titleMatches = $search->searchTitle( $rewritten );
311 $textMatches = $search->searchText( $rewritten );
313 $textStatus = null;
314 if ( $textMatches instanceof Status ) {
315 $textStatus = $textMatches;
316 $textMatches = $textStatus->getValue();
319 // Get number of results
320 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
321 if ( $titleMatches ) {
322 $titleMatchesNum = $titleMatches->numRows();
323 $numTitleMatches = $titleMatches->getTotalHits();
325 if ( $textMatches ) {
326 $textMatchesNum = $textMatches->numRows();
327 $numTextMatches = $textMatches->getTotalHits();
328 if ( $textMatchesNum > 0 ) {
329 $search->augmentSearchResults( $textMatches );
332 $num = $titleMatchesNum + $textMatchesNum;
333 $totalRes = $numTitleMatches + $numTextMatches;
335 // start rendering the page
336 $out->enableOOUI();
337 $out->addHTML( $formWidget->render(
338 $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch()
339 ) );
341 // did you mean... suggestions
342 if ( $textMatches ) {
343 $dymWidget = new MediaWiki\Widget\Search\DidYouMeanWidget( $this );
344 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
347 $out->addHTML( "<div class='searchresults'>" );
349 $hasErrors = $textStatus && $textStatus->getErrors();
350 $hasOtherResults = $textMatches &&
351 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
353 if ( $hasErrors ) {
354 list( $error, $warning ) = $textStatus->splitByErrorType();
355 if ( $error->getErrors() ) {
356 $out->addHTML( Html::rawElement(
357 'div',
358 [ 'class' => 'errorbox' ],
359 $error->getHTML( 'search-error' )
360 ) );
362 if ( $warning->getErrors() ) {
363 $out->addHTML( Html::rawElement(
364 'div',
365 [ 'class' => 'warningbox' ],
366 $warning->getHTML( 'search-warning' )
367 ) );
371 // Show the create link ahead
372 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
374 Hooks::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
376 // If we have no results and have not already displayed an error message
377 if ( $num === 0 && !$hasErrors ) {
378 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
379 $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
380 wfEscapeWikiText( $term )
381 ] );
384 // Although $num might be 0 there can still be secondary or inline
385 // results to display.
386 $linkRenderer = $this->getLinkRenderer();
387 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
388 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
389 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
390 $this,
391 $sidebarResultWidget,
392 $linkRenderer,
393 MediaWikiServices::getInstance()->getInterwikiLookup()
395 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
397 $out->addHTML( $widget->render(
398 $term, $this->offset, $titleMatches, $textMatches
399 ) );
401 if ( $titleMatches ) {
402 $titleMatches->free();
405 if ( $textMatches ) {
406 $textMatches->free();
409 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
411 // prev/next links
412 if ( $totalRes > $this->limit || $this->offset ) {
413 $prevnext = $this->getLanguage()->viewPrevNext(
414 $this->getPageTitle(),
415 $this->offset,
416 $this->limit,
417 $this->powerSearchOptions() + [ 'search' => $term ],
418 $this->limit + $this->offset >= $totalRes
420 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
423 // Close <div class='searchresults'>
424 $out->addHTML( "</div>" );
426 Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
430 * @param Title $title
431 * @param int $num The number of search results found
432 * @param null|SearchResultSet $titleMatches Results from title search
433 * @param null|SearchResultSet $textMatches Results from text search
435 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
436 // show direct page/create link if applicable
438 // Check DBkey !== '' in case of fragment link only.
439 if ( is_null( $title ) || $title->getDBkey() === ''
440 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
441 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
443 // invalid title
444 // preserve the paragraph for margins etc...
445 $this->getOutput()->addHTML( '<p></p>' );
447 return;
450 $messageName = 'searchmenu-new-nocreate';
451 $linkClass = 'mw-search-createlink';
453 if ( !$title->isExternal() ) {
454 if ( $title->isKnown() ) {
455 $messageName = 'searchmenu-exists';
456 $linkClass = 'mw-search-exists';
457 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
458 $messageName = 'searchmenu-new';
462 $params = [
463 $messageName,
464 wfEscapeWikiText( $title->getPrefixedText() ),
465 Message::numParam( $num )
467 Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
469 // Extensions using the hook might still return an empty $messageName
470 if ( $messageName ) {
471 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
472 } else {
473 // preserve the paragraph for margins etc...
474 $this->getOutput()->addHTML( '<p></p>' );
479 * Sets up everything for the HTML output page including styles, javascript,
480 * page title, etc.
482 * @param string $term
484 protected function setupPage( $term ) {
485 $out = $this->getOutput();
487 $this->setHeaders();
488 $this->outputHeader();
489 // TODO: Is this true? The namespace remember uses a user token
490 // on save.
491 $out->allowClickjacking();
492 $this->addHelpLink( 'Help:Searching' );
494 if ( strval( $term ) !== '' ) {
495 $out->setPageTitle( $this->msg( 'searchresults' ) );
496 $out->setHTMLTitle( $this->msg( 'pagetitle' )
497 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
498 ->inContentLanguage()->text()
502 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
503 $out->addModules( 'mediawiki.special.search' );
504 $out->addModuleStyles( [
505 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
506 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
507 ] );
511 * Return true if current search is a power (advanced) search
513 * @return bool
515 protected function isPowerSearch() {
516 return $this->profile === 'advanced';
520 * Extract "power search" namespace settings from the request object,
521 * returning a list of index numbers to search.
523 * @param WebRequest $request
524 * @return array
526 protected function powerSearch( &$request ) {
527 $arr = [];
528 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
529 if ( $request->getCheck( 'ns' . $ns ) ) {
530 $arr[] = $ns;
534 return $arr;
538 * Reconstruct the 'power search' options for links
539 * TODO: Instead of exposing this publicly, could we instead expose
540 * a function for creating search links?
542 * @return array
544 public function powerSearchOptions() {
545 $opt = [];
546 if ( $this->isPowerSearch() ) {
547 foreach ( $this->namespaces as $n ) {
548 $opt['ns' . $n] = 1;
550 } else {
551 $opt['profile'] = $this->profile;
554 return $opt + $this->extraParams;
558 * Save namespace preferences when we're supposed to
560 * @return bool Whether we wrote something
562 protected function saveNamespaces() {
563 $user = $this->getUser();
564 $request = $this->getRequest();
566 if ( $user->isLoggedIn() &&
567 $user->matchEditToken(
568 $request->getVal( 'nsRemember' ),
569 'searchnamespace',
570 $request
571 ) && !wfReadOnly()
573 // Reset namespace preferences: namespaces are not searched
574 // when they're not mentioned in the URL parameters.
575 foreach ( MWNamespace::getValidNamespaces() as $n ) {
576 $user->setOption( 'searchNs' . $n, false );
578 // The request parameters include all the namespaces to be searched.
579 // Even if they're the same as an existing profile, they're not eaten.
580 foreach ( $this->namespaces as $n ) {
581 $user->setOption( 'searchNs' . $n, true );
584 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
585 $user->saveSettings();
586 } );
588 return true;
591 return false;
595 * @return array
597 protected function getSearchProfiles() {
598 // Builds list of Search Types (profiles)
599 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
600 $defaultNs = $this->searchConfig->defaultNamespaces();
601 $profiles = [
602 'default' => [
603 'message' => 'searchprofile-articles',
604 'tooltip' => 'searchprofile-articles-tooltip',
605 'namespaces' => $defaultNs,
606 'namespace-messages' => $this->searchConfig->namespacesAsText(
607 $defaultNs
610 'images' => [
611 'message' => 'searchprofile-images',
612 'tooltip' => 'searchprofile-images-tooltip',
613 'namespaces' => [ NS_FILE ],
615 'all' => [
616 'message' => 'searchprofile-everything',
617 'tooltip' => 'searchprofile-everything-tooltip',
618 'namespaces' => $nsAllSet,
620 'advanced' => [
621 'message' => 'searchprofile-advanced',
622 'tooltip' => 'searchprofile-advanced-tooltip',
623 'namespaces' => self::NAMESPACES_CURRENT,
627 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
629 foreach ( $profiles as &$data ) {
630 if ( !is_array( $data['namespaces'] ) ) {
631 continue;
633 sort( $data['namespaces'] );
636 return $profiles;
640 * @since 1.18
642 * @return SearchEngine
644 public function getSearchEngine() {
645 if ( $this->searchEngine === null ) {
646 $this->searchEngine = $this->searchEngineType ?
647 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
648 MediaWikiServices::getInstance()->newSearchEngine();
651 return $this->searchEngine;
655 * Current search profile.
656 * @return null|string
658 function getProfile() {
659 return $this->profile;
663 * Current namespaces.
664 * @return array
666 function getNamespaces() {
667 return $this->namespaces;
671 * Users of hook SpecialSearchSetupEngine can use this to
672 * add more params to links to not lose selection when
673 * user navigates search results.
674 * @since 1.18
676 * @param string $key
677 * @param mixed $value
679 public function setExtraParam( $key, $value ) {
680 $this->extraParams[$key] = $value;
683 protected function getGroupName() {
684 return 'pages';