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
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
30 class SpecialSearch
extends SpecialPage
{
32 * Current search profile. Search profile is just a name that identifies
33 * the active search tab on the search page (content, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
47 /** @var array For links */
48 protected $extraParams = [];
51 * @var string The prefix url parameter. Set on the searcher and the
52 * is expected to treat it as prefix filter on titles.
59 protected $limit, $offset;
64 protected $namespaces;
74 protected $runSuggestion = true;
77 * Names of the wikis, in format: Interwiki prefix -> caption
80 protected $customCaptions;
82 const NAMESPACES_CURRENT
= 'sense';
84 public function __construct() {
85 parent
::__construct( 'Search' );
93 public function execute( $par ) {
95 $this->outputHeader();
96 $out = $this->getOutput();
97 $out->allowClickjacking();
98 $out->addModuleStyles( [
99 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
100 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
102 $this->addHelpLink( 'Help:Searching' );
104 // Strip underscores from title parameter; most of the time we'll want
105 // text form here. But don't strip underscores from actual text params!
106 $titleParam = str_replace( '_', ' ', $par );
108 $request = $this->getRequest();
110 // Fetch the search term
111 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
114 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
115 $this->saveNamespaces();
116 // Remove the token from the URL to prevent the user from inadvertently
117 // exposing it (e.g. by pasting it into a public wiki page) or undoing
118 // later settings changes (e.g. by reloading the page).
119 $query = $request->getValues();
120 unset( $query['title'], $query['nsRemember'] );
121 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
125 $out->addJsConfigVars( [ 'searchTerm' => $search ] );
126 $this->searchEngineType
= $request->getVal( 'srbackend' );
128 if ( $request->getVal( 'fulltext' )
129 ||
!is_null( $request->getVal( 'offset' ) )
131 $this->showResults( $search );
133 $this->goResult( $search );
138 * Set up basic search parameters from the request and user settings.
140 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
142 public function load() {
143 $request = $this->getRequest();
144 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
145 $this->mPrefix
= $request->getVal( 'prefix', '' );
147 $user = $this->getUser();
149 # Extract manually requested namespaces
150 $nslist = $this->powerSearch( $request );
151 if ( !count( $nslist ) ) {
152 # Fallback to user preference
153 $nslist = SearchEngine
::userNamespaces( $user );
157 if ( !count( $nslist ) ) {
158 $profile = 'default';
161 $profile = $request->getVal( 'profile', $profile );
162 $profiles = $this->getSearchProfiles();
163 if ( $profile === null ) {
164 // BC with old request format
165 $profile = 'advanced';
166 foreach ( $profiles as $key => $data ) {
167 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
171 $this->namespaces
= $nslist;
172 } elseif ( $profile === 'advanced' ) {
173 $this->namespaces
= $nslist;
175 if ( isset( $profiles[$profile]['namespaces'] ) ) {
176 $this->namespaces
= $profiles[$profile]['namespaces'];
178 // Unknown profile requested
179 $profile = 'default';
180 $this->namespaces
= $profiles['default']['namespaces'];
184 $this->fulltext
= $request->getVal( 'fulltext' );
185 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
186 $this->profile
= $profile;
190 * If an exact title match can be found, jump straight ahead to it.
192 * @param string $term
194 public function goResult( $term ) {
195 $this->setupPage( $term );
196 # Try to go to page as entered.
197 $title = Title
::newFromText( $term );
198 # If the string cannot be used to create a title
199 if ( is_null( $title ) ) {
200 $this->showResults( $term );
204 # If there's an exact or very near match, jump right there.
205 $title = SearchEngine
::getNearMatch( $term );
207 if ( !is_null( $title ) &&
208 Hooks
::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] )
210 if ( $url === null ) {
211 $url = $title->getFullURL();
213 $this->getOutput()->redirect( $url );
217 # No match, generate an edit URL
218 $title = Title
::newFromText( $term );
219 if ( !is_null( $title ) ) {
220 Hooks
::run( 'SpecialSearchNogomatch', [ &$title ] );
222 $this->showResults( $term );
226 * @param string $term
228 public function showResults( $term ) {
231 $search = $this->getSearchEngine();
232 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
233 $search->setLimitOffset( $this->limit
, $this->offset
);
234 $search->setNamespaces( $this->namespaces
);
235 $search->prefix
= $this->mPrefix
;
236 $term = $search->transformSearchTerm( $term );
238 Hooks
::run( 'SpecialSearchSetupEngine', [ $this, $this->profile
, $search ] );
240 $this->setupPage( $term );
242 $out = $this->getOutput();
244 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
245 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
246 if ( $searchFowardUrl ) {
247 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
248 $out->redirect( $url );
251 Xml
::openElement( 'fieldset' ) .
252 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
255 [ 'class' => 'mw-searchdisabled' ],
256 $this->msg( 'searchdisabled' )->text()
258 $this->msg( 'googlesearch' )->rawParams(
259 htmlspecialchars( $term ),
261 $this->msg( 'searchbutton' )->escaped()
263 Xml
::closeElement( 'fieldset' )
270 $title = Title
::newFromText( $term );
271 $showSuggestion = $title === null ||
!$title->isKnown();
272 $search->setShowSuggestion( $showSuggestion );
274 // fetch search results
275 $rewritten = $search->replacePrefixes( $term );
277 $titleMatches = $search->searchTitle( $rewritten );
278 $textMatches = $search->searchText( $rewritten );
281 if ( $textMatches instanceof Status
) {
282 $textStatus = $textMatches;
286 // did you mean... suggestions
287 $didYouMeanHtml = '';
288 if ( $showSuggestion && $textMatches && !$textStatus ) {
289 if ( $textMatches->hasRewrittenQuery() ) {
290 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
291 } elseif ( $textMatches->hasSuggestion() ) {
292 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
296 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
297 # Hook requested termination
301 // start rendering the page
306 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
308 'action' => wfScript(),
313 // Get number of results
314 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
315 if ( $titleMatches ) {
316 $titleMatchesNum = $titleMatches->numRows();
317 $numTitleMatches = $titleMatches->getTotalHits();
319 if ( $textMatches ) {
320 $textMatchesNum = $textMatches->numRows();
321 $numTextMatches = $textMatches->getTotalHits();
323 $num = $titleMatchesNum +
$textMatchesNum;
324 $totalRes = $numTitleMatches +
$numTextMatches;
328 # This is an awful awful ID name. It's not a table, but we
329 # named it poorly from when this was a table so now we're
331 Xml
::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
332 $this->shortDialog( $term, $num, $totalRes ) .
333 Xml
::closeElement( 'div' ) .
334 $this->searchProfileTabs( $term ) .
335 $this->searchOptions( $term ) .
336 Xml
::closeElement( 'form' ) .
340 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
341 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
342 // Empty query -- straight view of search form
346 $out->addHTML( "<div class='searchresults'>" );
350 if ( $num ||
$this->offset
) {
351 // Show the create link ahead
352 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
353 if ( $totalRes > $this->limit ||
$this->offset
) {
354 if ( $this->searchEngineType
!== null ) {
355 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
357 $prevnext = $this->getLanguage()->viewPrevNext(
358 $this->getPageTitle(),
361 $this->powerSearchOptions() +
[ 'search' => $term ],
362 $this->limit +
$this->offset
>= $totalRes
366 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
368 $out->parserOptions()->setEditSection( false );
369 if ( $titleMatches ) {
370 if ( $numTitleMatches > 0 ) {
371 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
372 $out->addHTML( $this->showMatches( $titleMatches ) );
374 $titleMatches->free();
376 if ( $textMatches && !$textStatus ) {
377 // output appropriate heading
378 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
379 $out->addHTML( '<div class="visualClear"></div>' );
380 // if no title matches the heading is redundant
381 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
385 if ( $numTextMatches > 0 ) {
386 $out->addHTML( $this->showMatches( $textMatches ) );
389 // show secondary interwiki results if any
390 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
391 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
392 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
396 $hasOtherResults = $textMatches &&
397 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
401 $out->addHTML( '<div class="error">' .
402 $textStatus->getMessage( 'search-error' ) . '</div>' );
404 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
405 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
406 [ $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
407 wfEscapeWikiText( $term )
412 if ( $hasOtherResults ) {
413 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
414 as $interwiki => $interwikiResult ) {
415 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
416 // ignore bad interwikis for now
420 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
424 if ( $textMatches ) {
425 $textMatches->free();
428 $out->addHTML( '<div class="visualClear"></div>' );
431 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
434 $out->addHTML( "</div>" );
436 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
441 * Produce wiki header for interwiki results
442 * @param string $interwiki Interwiki name
443 * @param SearchResultSet $interwikiResult The result set
446 protected function interwikiHeader( $interwiki, $interwikiResult ) {
447 // TODO: we need to figure out how to name wikis correctly
448 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
449 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
453 * Decide if the suggested query should be run, and it's results returned
454 * instead of the provided $textMatches
456 * @param SearchResultSet $textMatches The results of a users query
459 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
460 if ( !$this->runSuggestion ||
461 !$textMatches->hasSuggestion() ||
462 $textMatches->numRows() > 0 ||
463 $textMatches->searchContainedSyntax()
468 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
472 * Generates HTML shown to the user when we have a suggestion about a query
473 * that might give more results than their current query.
475 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
476 # mirror Go/Search behavior of original request ..
477 $params = [ 'search' => $textMatches->getSuggestionQuery() ];
478 if ( $this->fulltext
!= null ) {
479 $params['fulltext'] = $this->fulltext
;
481 $stParams = array_merge( $params, $this->powerSearchOptions() );
483 $suggest = Linker
::linkKnown(
484 $this->getPageTitle(),
485 $textMatches->getSuggestionSnippet() ?
: null,
486 [ 'id' => 'mw-search-DYM-suggestion' ],
490 # HTML of did you mean... search suggestion link
491 return Html
::rawElement(
493 [ 'class' => 'searchdidyoumean' ],
494 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
499 * Generates HTML shown to user when their query has been internally rewritten,
500 * and the results of the rewritten query are being returned.
502 * @param string $term The users search input
503 * @param SearchResultSet $textMatches The response to the users initial search request
504 * @return string HTML linking the user to their original $term query, and the one
505 * suggested by $textMatches.
507 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
508 // Showing results for '$rewritten'
509 // Search instead for '$orig'
511 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
512 if ( $this->fulltext
!= null ) {
513 $params['fulltext'] = $this->fulltext
;
515 $stParams = array_merge( $params, $this->powerSearchOptions() );
517 $rewritten = Linker
::linkKnown(
518 $this->getPageTitle(),
519 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
520 [ 'id' => 'mw-search-DYM-rewritten' ],
524 $stParams['search'] = $term;
525 $stParams['runsuggestion'] = 0;
526 $original = Linker
::linkKnown(
527 $this->getPageTitle(),
528 htmlspecialchars( $term ),
529 [ 'id' => 'mw-search-DYM-original' ],
533 return Html
::rawElement(
535 [ 'class' => 'searchdidyoumean' ],
536 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
541 * @param Title $title
542 * @param int $num The number of search results found
543 * @param null|SearchResultSet $titleMatches Results from title search
544 * @param null|SearchResultSet $textMatches Results from text search
546 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
547 // show direct page/create link if applicable
549 // Check DBkey !== '' in case of fragment link only.
550 if ( is_null( $title ) ||
$title->getDBkey() === ''
551 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
552 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
555 // preserve the paragraph for margins etc...
556 $this->getOutput()->addHTML( '<p></p>' );
561 $messageName = 'searchmenu-new-nocreate';
562 $linkClass = 'mw-search-createlink';
564 if ( !$title->isExternal() ) {
565 if ( $title->isKnown() ) {
566 $messageName = 'searchmenu-exists';
567 $linkClass = 'mw-search-exists';
568 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
569 $messageName = 'searchmenu-new';
575 wfEscapeWikiText( $title->getPrefixedText() ),
576 Message
::numParam( $num )
578 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
580 // Extensions using the hook might still return an empty $messageName
581 if ( $messageName ) {
582 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
584 // preserve the paragraph for margins etc...
585 $this->getOutput()->addHTML( '<p></p>' );
590 * @param string $term
592 protected function setupPage( $term ) {
593 $out = $this->getOutput();
594 if ( strval( $term ) !== '' ) {
595 $out->setPageTitle( $this->msg( 'searchresults' ) );
596 $out->setHTMLTitle( $this->msg( 'pagetitle' )
597 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
598 ->inContentLanguage()->text()
601 // add javascript specific to special:search
602 $out->addModules( 'mediawiki.special.search' );
606 * Return true if current search is a power (advanced) search
610 protected function isPowerSearch() {
611 return $this->profile
=== 'advanced';
615 * Extract "power search" namespace settings from the request object,
616 * returning a list of index numbers to search.
618 * @param WebRequest $request
621 protected function powerSearch( &$request ) {
623 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
624 if ( $request->getCheck( 'ns' . $ns ) ) {
633 * Reconstruct the 'power search' options for links
637 protected function powerSearchOptions() {
639 if ( !$this->isPowerSearch() ) {
640 $opt['profile'] = $this->profile
;
642 foreach ( $this->namespaces
as $n ) {
647 return $opt +
$this->extraParams
;
651 * Save namespace preferences when we're supposed to
653 * @return bool Whether we wrote something
655 protected function saveNamespaces() {
656 $user = $this->getUser();
657 $request = $this->getRequest();
659 if ( $user->isLoggedIn() &&
660 $user->matchEditToken(
661 $request->getVal( 'nsRemember' ),
666 // Reset namespace preferences: namespaces are not searched
667 // when they're not mentioned in the URL parameters.
668 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
669 $user->setOption( 'searchNs' . $n, false );
671 // The request parameters include all the namespaces to be searched.
672 // Even if they're the same as an existing profile, they're not eaten.
673 foreach ( $this->namespaces
as $n ) {
674 $user->setOption( 'searchNs' . $n, true );
677 $user->saveSettings();
685 * Show whole set of results
687 * @param SearchResultSet $matches
688 * @param string $interwiki Interwiki name
692 protected function showMatches( &$matches, $interwiki = null ) {
695 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
697 $result = $matches->next();
698 $pos = $this->offset
;
700 if ( $result && $interwiki ) {
701 $out .= $this->interwikiHeader( $interwiki, $result );
704 $out .= "<ul class='mw-search-results'>\n";
706 $out .= $this->showHit( $result, $terms, ++
$pos );
707 $result = $matches->next();
711 // convert the whole thing to desired language variant
712 $out = $wgContLang->convert( $out );
718 * Format a single hit result
720 * @param SearchResult $result
721 * @param array $terms Terms to highlight
722 * @param int $position Position within the search results, including offset.
726 protected function showHit( $result, $terms, $position ) {
728 if ( $result->isBrokenTitle() ) {
732 $title = $result->getTitle();
734 $titleSnippet = $result->getTitleSnippet();
736 if ( $titleSnippet == '' ) {
737 $titleSnippet = null;
740 $link_t = clone $title;
743 Hooks
::run( 'ShowSearchHitTitle',
744 [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
746 $link = Linker
::linkKnown(
749 [ 'data-serp-pos' => $position ], // HTML attributes
753 // If page content is not readable, just return the title.
754 // This is not quite safe, but better than showing excerpts from non-readable pages
755 // Note that hiding the entry entirely would screw up paging.
756 if ( !$title->userCan( 'read', $this->getUser() ) ) {
757 return "<li>{$link}</li>\n";
760 // If the page doesn't *exist*... our search index is out of date.
761 // The least confusing at this point is to drop the result.
762 // You may get less results, but... oh well. :P
763 if ( $result->isMissingRevision() ) {
767 // format redirects / relevant sections
768 $redirectTitle = $result->getRedirectTitle();
769 $redirectText = $result->getRedirectSnippet();
770 $sectionTitle = $result->getSectionTitle();
771 $sectionText = $result->getSectionSnippet();
772 $categorySnippet = $result->getCategorySnippet();
775 if ( !is_null( $redirectTitle ) ) {
776 if ( $redirectText == '' ) {
777 $redirectText = null;
780 $redirect = "<span class='searchalttitle'>" .
781 $this->msg( 'search-redirect' )->rawParams(
782 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
787 if ( !is_null( $sectionTitle ) ) {
788 if ( $sectionText == '' ) {
792 $section = "<span class='searchalttitle'>" .
793 $this->msg( 'search-section' )->rawParams(
794 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
799 if ( $categorySnippet ) {
800 $category = "<span class='searchalttitle'>" .
801 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
805 // format text extract
806 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
808 $lang = $this->getLanguage();
810 // format description
811 $byteSize = $result->getByteSize();
812 $wordCount = $result->getWordCount();
813 $timestamp = $result->getTimestamp();
814 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
815 ->numParams( $wordCount )->escaped();
817 if ( $title->getNamespace() == NS_CATEGORY
) {
818 $cat = Category
::newFromTitle( $title );
819 $size = $this->msg( 'search-result-category-size' )
820 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
824 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
827 // Include a thumbnail for media files...
828 if ( $title->getNamespace() == NS_FILE
) {
829 $img = $result->getFile();
830 $img = $img ?
: wfFindFile( $title );
831 if ( $result->isFileMatch() ) {
832 $fileMatch = "<span class='searchalttitle'>" .
833 $this->msg( 'search-file-match' )->escaped() . "</span>";
836 $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
838 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
839 // Float doesn't seem to interact well with the bullets.
840 // Table messes up vertical alignment of the bullets.
841 // Bullets are therefore disabled (didn't look great anyway).
843 '<table class="searchResultImage">' .
845 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
846 $thumb->toHtml( [ 'desc-link' => true ] ) .
848 '<td style="vertical-align: top;">' .
849 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
851 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
864 if ( Hooks
::run( 'ShowSearchHit', [
865 $this, $result, $terms,
866 &$link, &$redirect, &$section, &$extract,
867 &$score, &$size, &$date, &$related,
870 $html = "<li><div class='mw-search-result-heading'>" .
871 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
872 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
880 * Extract custom captions from search-interwiki-custom message
882 protected function getCustomCaptions() {
883 if ( is_null( $this->customCaptions
) ) {
884 $this->customCaptions
= [];
885 // format per line <iwprefix>:<caption>
886 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
887 foreach ( $customLines as $line ) {
888 $parts = explode( ":", $line, 2 );
889 if ( count( $parts ) == 2 ) { // validate line
890 $this->customCaptions
[$parts[0]] = $parts[1];
897 * Show results from other wikis
899 * @param SearchResultSet|array $matches
900 * @param string $query
904 protected function showInterwiki( $matches, $query ) {
907 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
908 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
909 $out .= "<ul class='mw-search-iwresults'>\n";
911 // work out custom project captions
912 $this->getCustomCaptions();
914 if ( !is_array( $matches ) ) {
915 $matches = [ $matches ];
918 foreach ( $matches as $set ) {
920 $result = $set->next();
922 $out .= $this->showInterwikiHit( $result, $prev, $query );
923 $prev = $result->getInterwikiPrefix();
924 $result = $set->next();
928 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
929 $out .= "</ul></div>\n";
931 // convert the whole thing to desired language variant
932 $out = $wgContLang->convert( $out );
938 * Show single interwiki link
940 * @param SearchResult $result
941 * @param string $lastInterwiki
942 * @param string $query
946 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
948 if ( $result->isBrokenTitle() ) {
952 $title = $result->getTitle();
954 $titleSnippet = $result->getTitleSnippet();
956 if ( $titleSnippet == '' ) {
957 $titleSnippet = null;
960 $link = Linker
::linkKnown(
965 // format redirect if any
966 $redirectTitle = $result->getRedirectTitle();
967 $redirectText = $result->getRedirectSnippet();
969 if ( !is_null( $redirectTitle ) ) {
970 if ( $redirectText == '' ) {
971 $redirectText = null;
974 $redirect = "<span class='searchalttitle'>" .
975 $this->msg( 'search-redirect' )->rawParams(
976 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
981 // display project name
982 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
983 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions
) ) {
984 // captions from 'search-interwiki-custom'
985 $caption = $this->customCaptions
[$title->getInterwiki()];
987 // default is to show the hostname of the other wiki which might suck
988 // if there are many wikis on one hostname
989 $parsed = wfParseUrl( $title->getFullURL() );
990 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
992 // "more results" link (special page stuff could be localized, but we might not know target lang)
993 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
994 $searchLink = Linker
::linkKnown(
996 $this->msg( 'search-interwiki-more' )->text(),
1000 'fulltext' => 'Search'
1003 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1004 {$searchLink}</span>{$caption}</div>\n<ul>";
1007 $out .= "<li>{$link} {$redirect}</li>\n";
1013 * Generates the power search box at [[Special:Search]]
1015 * @param string $term Search term
1016 * @param array $opts
1017 * @return string HTML form
1019 protected function powerSearchBox( $term, $opts ) {
1022 // Groups namespaces into rows according to subject
1024 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
1025 $subject = MWNamespace
::getSubject( $namespace );
1026 if ( !array_key_exists( $subject, $rows ) ) {
1027 $rows[$subject] = "";
1030 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1031 if ( $name == '' ) {
1032 $name = $this->msg( 'blanknamespace' )->text();
1036 Xml
::openElement( 'td' ) .
1040 "mw-search-ns{$namespace}",
1041 in_array( $namespace, $this->namespaces
)
1043 Xml
::closeElement( 'td' );
1046 $rows = array_values( $rows );
1047 $numRows = count( $rows );
1049 // Lays out namespaces in multiple floating two-column tables so they'll
1050 // be arranged nicely while still accommodating different screen widths
1051 $namespaceTables = '';
1052 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
1053 $namespaceTables .= Xml
::openElement( 'table' );
1055 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
1056 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
1059 $namespaceTables .= Xml
::closeElement( 'table' );
1062 $showSections = [ 'namespaceTables' => $namespaceTables ];
1064 Hooks
::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1067 foreach ( $opts as $key => $value ) {
1068 $hidden .= Html
::hidden( $key, $value );
1071 # Stuff to feed saveNamespaces()
1073 $user = $this->getUser();
1074 if ( $user->isLoggedIn() ) {
1075 $remember .= Xml
::checkLabel(
1076 $this->msg( 'powersearch-remember' )->text(),
1078 'mw-search-powersearch-remember',
1080 // The token goes here rather than in a hidden field so it
1081 // is only sent when necessary (not every form submission).
1082 [ 'value' => $user->getEditToken(
1089 // Return final output
1090 return Xml
::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1091 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1092 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1093 Xml
::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1094 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1095 implode( Xml
::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1097 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1099 Xml
::closeElement( 'fieldset' );
1105 protected function getSearchProfiles() {
1106 // Builds list of Search Types (profiles)
1107 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1111 'message' => 'searchprofile-articles',
1112 'tooltip' => 'searchprofile-articles-tooltip',
1113 'namespaces' => SearchEngine
::defaultNamespaces(),
1114 'namespace-messages' => SearchEngine
::namespacesAsText(
1115 SearchEngine
::defaultNamespaces()
1119 'message' => 'searchprofile-images',
1120 'tooltip' => 'searchprofile-images-tooltip',
1121 'namespaces' => [ NS_FILE
],
1124 'message' => 'searchprofile-everything',
1125 'tooltip' => 'searchprofile-everything-tooltip',
1126 'namespaces' => $nsAllSet,
1129 'message' => 'searchprofile-advanced',
1130 'tooltip' => 'searchprofile-advanced-tooltip',
1131 'namespaces' => self
::NAMESPACES_CURRENT
,
1135 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
1137 foreach ( $profiles as &$data ) {
1138 if ( !is_array( $data['namespaces'] ) ) {
1141 sort( $data['namespaces'] );
1148 * @param string $term
1151 protected function searchProfileTabs( $term ) {
1152 $out = Xml
::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1155 if ( $this->startsWithImage( $term ) ) {
1157 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1160 $profiles = $this->getSearchProfiles();
1161 $lang = $this->getLanguage();
1163 // Outputs XML for Search Types
1164 $out .= Xml
::openElement( 'div', [ 'class' => 'search-types' ] );
1165 $out .= Xml
::openElement( 'ul' );
1166 foreach ( $profiles as $id => $profile ) {
1167 if ( !isset( $profile['parameters'] ) ) {
1168 $profile['parameters'] = [];
1170 $profile['parameters']['profile'] = $id;
1172 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1173 $lang->commaList( $profile['namespace-messages'] ) : null;
1177 'class' => $this->profile
=== $id ?
'current' : 'normal'
1179 $this->makeSearchLink(
1182 $this->msg( $profile['message'] )->text(),
1183 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1184 $profile['parameters']
1188 $out .= Xml
::closeElement( 'ul' );
1189 $out .= Xml
::closeElement( 'div' );
1190 $out .= Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1191 $out .= Xml
::closeElement( 'div' );
1197 * @param string $term Search term
1200 protected function searchOptions( $term ) {
1203 $opts['profile'] = $this->profile
;
1205 if ( $this->isPowerSearch() ) {
1206 $out .= $this->powerSearchBox( $term, $opts );
1209 Hooks
::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile
, $term, $opts ] );
1217 * @param string $term
1218 * @param int $resultsShown
1219 * @param int $totalNum
1222 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1223 $searchWidget = new MediaWiki\Widget\
SearchInputWidget( [
1224 'id' => 'searchText',
1226 'autofocus' => trim( $term ) === '',
1231 Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1232 Html
::hidden( 'profile', $this->profile
) .
1233 Html
::hidden( 'fulltext', 'Search' ) .
1235 new OOUI\
ButtonInputWidget( [
1237 'label' => $this->msg( 'searchbutton' )->text(),
1238 'flags' => [ 'progressive', 'primary' ],
1242 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1243 $top = $this->msg( 'search-showingresults' )
1244 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1245 ->numParams( $resultsShown )
1247 $out .= Xml
::tags( 'div', [ 'class' => 'results-info' ], $top ) .
1248 Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1255 * Make a search link with some target namespaces
1257 * @param string $term
1258 * @param array $namespaces Ignored
1259 * @param string $label Link's text
1260 * @param string $tooltip Link's tooltip
1261 * @param array $params Query string parameters
1262 * @return string HTML fragment
1264 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1266 foreach ( $namespaces as $n ) {
1267 $opt['ns' . $n] = 1;
1270 $stParams = array_merge(
1273 'fulltext' => $this->msg( 'search' )->text()
1278 return Xml
::element(
1281 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1289 * Check if query starts with image: prefix
1291 * @param string $term The string to check
1294 protected function startsWithImage( $term ) {
1297 $parts = explode( ':', $term );
1298 if ( count( $parts ) > 1 ) {
1299 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1306 * Check if query starts with all: prefix
1308 * @param string $term The string to check
1311 protected function startsWithAll( $term ) {
1313 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1315 $parts = explode( ':', $term );
1316 if ( count( $parts ) > 1 ) {
1317 return $parts[0] == $allkeyword;
1326 * @return SearchEngine
1328 public function getSearchEngine() {
1329 if ( $this->searchEngine
=== null ) {
1330 $this->searchEngine
= $this->searchEngineType ?
1331 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1334 return $this->searchEngine
;
1338 * Current search profile.
1339 * @return null|string
1341 function getProfile() {
1342 return $this->profile
;
1346 * Current namespaces.
1349 function getNamespaces() {
1350 return $this->namespaces
;
1354 * Users of hook SpecialSearchSetupEngine can use this to
1355 * add more params to links to not lose selection when
1356 * user navigates search results.
1359 * @param string $key
1360 * @param mixed $value
1362 public function setExtraParam( $key, $value ) {
1363 $this->extraParams
[$key] = $value;
1366 protected function getGroupName() {