dfab8d437ccc22b09f31c6b47df856082f621318
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',
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;
327 # This is an awful awful ID name. It's not a table, but we
328 # named it poorly from when this was a table so now we're
330 Xml
::openElement( 'div', [ 'id' => 'mw-search-top-table' ] ) .
331 $this->shortDialog( $term, $num, $totalRes ) .
332 Xml
::closeElement( 'div' ) .
333 $this->searchProfileTabs( $term ) .
334 $this->searchOptions( $term ) .
335 Xml
::closeElement( 'form' ) .
339 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
340 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
341 // Empty query -- straight view of search form
345 $out->addHTML( "<div class='searchresults'>" );
349 if ( $num ||
$this->offset
) {
350 // Show the create link ahead
351 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
352 if ( $totalRes > $this->limit ||
$this->offset
) {
353 if ( $this->searchEngineType
!== null ) {
354 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
356 $prevnext = $this->getLanguage()->viewPrevNext(
357 $this->getPageTitle(),
360 $this->powerSearchOptions() +
[ 'search' => $term ],
361 $this->limit +
$this->offset
>= $totalRes
365 Hooks
::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
367 $out->parserOptions()->setEditSection( false );
368 if ( $titleMatches ) {
369 if ( $numTitleMatches > 0 ) {
370 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
371 $out->addHTML( $this->showMatches( $titleMatches ) );
373 $titleMatches->free();
375 if ( $textMatches && !$textStatus ) {
376 // output appropriate heading
377 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
378 // if no title matches the heading is redundant
379 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
383 if ( $numTextMatches > 0 ) {
384 $out->addHTML( $this->showMatches( $textMatches ) );
387 // show secondary interwiki results if any
388 if ( $textMatches->hasInterwikiResults( SearchResultSet
::SECONDARY_RESULTS
) ) {
389 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
390 SearchResultSet
::SECONDARY_RESULTS
), $term ) );
394 $hasOtherResults = $textMatches &&
395 $textMatches->hasInterwikiResults( SearchResultSet
::INLINE_RESULTS
);
399 $out->addHTML( '<div class="error">' .
400 $textStatus->getMessage( 'search-error' ) . '</div>' );
402 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
403 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
404 [ $hasOtherResults ?
'search-nonefound-thiswiki' : 'search-nonefound',
405 wfEscapeWikiText( $term )
410 if ( $hasOtherResults ) {
411 foreach ( $textMatches->getInterwikiResults( SearchResultSet
::INLINE_RESULTS
)
412 as $interwiki => $interwikiResult ) {
413 if ( $interwikiResult instanceof Status ||
$interwikiResult->numRows() == 0 ) {
414 // ignore bad interwikis for now
418 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
422 if ( $textMatches ) {
423 $textMatches->free();
426 $out->addHTML( '<div class="visualClear"></div>' );
429 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
432 $out->addHTML( "</div>" );
434 Hooks
::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
439 * Produce wiki header for interwiki results
440 * @param string $interwiki Interwiki name
441 * @param SearchResultSet $interwikiResult The result set
444 protected function interwikiHeader( $interwiki, $interwikiResult ) {
445 // TODO: we need to figure out how to name wikis correctly
446 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
447 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
451 * Decide if the suggested query should be run, and it's results returned
452 * instead of the provided $textMatches
454 * @param SearchResultSet $textMatches The results of a users query
457 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
458 if ( !$this->runSuggestion ||
459 !$textMatches->hasSuggestion() ||
460 $textMatches->numRows() > 0 ||
461 $textMatches->searchContainedSyntax()
466 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
470 * Generates HTML shown to the user when we have a suggestion about a query
471 * that might give more results than their current query.
473 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
474 # mirror Go/Search behavior of original request ..
475 $params = [ 'search' => $textMatches->getSuggestionQuery() ];
476 if ( $this->fulltext
!= null ) {
477 $params['fulltext'] = $this->fulltext
;
479 $stParams = array_merge( $params, $this->powerSearchOptions() );
481 $suggest = Linker
::linkKnown(
482 $this->getPageTitle(),
483 $textMatches->getSuggestionSnippet() ?
: null,
484 [ 'id' => 'mw-search-DYM-suggestion' ],
488 # HTML of did you mean... search suggestion link
489 return Html
::rawElement(
491 [ 'class' => 'searchdidyoumean' ],
492 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
497 * Generates HTML shown to user when their query has been internally rewritten,
498 * and the results of the rewritten query are being returned.
500 * @param string $term The users search input
501 * @param SearchResultSet $textMatches The response to the users initial search request
502 * @return string HTML linking the user to their original $term query, and the one
503 * suggested by $textMatches.
505 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
506 // Showing results for '$rewritten'
507 // Search instead for '$orig'
509 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
510 if ( $this->fulltext
!= null ) {
511 $params['fulltext'] = $this->fulltext
;
513 $stParams = array_merge( $params, $this->powerSearchOptions() );
515 $rewritten = Linker
::linkKnown(
516 $this->getPageTitle(),
517 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
518 [ 'id' => 'mw-search-DYM-rewritten' ],
522 $stParams['search'] = $term;
523 $stParams['runsuggestion'] = 0;
524 $original = Linker
::linkKnown(
525 $this->getPageTitle(),
526 htmlspecialchars( $term ),
527 [ 'id' => 'mw-search-DYM-original' ],
531 return Html
::rawElement(
533 [ 'class' => 'searchdidyoumean' ],
534 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
539 * @param Title $title
540 * @param int $num The number of search results found
541 * @param null|SearchResultSet $titleMatches Results from title search
542 * @param null|SearchResultSet $textMatches Results from text search
544 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
545 // show direct page/create link if applicable
547 // Check DBkey !== '' in case of fragment link only.
548 if ( is_null( $title ) ||
$title->getDBkey() === ''
549 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
550 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
553 // preserve the paragraph for margins etc...
554 $this->getOutput()->addHTML( '<p></p>' );
559 $messageName = 'searchmenu-new-nocreate';
560 $linkClass = 'mw-search-createlink';
562 if ( !$title->isExternal() ) {
563 if ( $title->isKnown() ) {
564 $messageName = 'searchmenu-exists';
565 $linkClass = 'mw-search-exists';
566 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
567 $messageName = 'searchmenu-new';
573 wfEscapeWikiText( $title->getPrefixedText() ),
574 Message
::numParam( $num )
576 Hooks
::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
578 // Extensions using the hook might still return an empty $messageName
579 if ( $messageName ) {
580 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
582 // preserve the paragraph for margins etc...
583 $this->getOutput()->addHTML( '<p></p>' );
588 * @param string $term
590 protected function setupPage( $term ) {
591 $out = $this->getOutput();
592 if ( strval( $term ) !== '' ) {
593 $out->setPageTitle( $this->msg( 'searchresults' ) );
594 $out->setHTMLTitle( $this->msg( 'pagetitle' )
595 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
596 ->inContentLanguage()->text()
599 // add javascript specific to special:search
600 $out->addModules( 'mediawiki.special.search' );
604 * Return true if current search is a power (advanced) search
608 protected function isPowerSearch() {
609 return $this->profile
=== 'advanced';
613 * Extract "power search" namespace settings from the request object,
614 * returning a list of index numbers to search.
616 * @param WebRequest $request
619 protected function powerSearch( &$request ) {
621 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
622 if ( $request->getCheck( 'ns' . $ns ) ) {
631 * Reconstruct the 'power search' options for links
635 protected function powerSearchOptions() {
637 if ( !$this->isPowerSearch() ) {
638 $opt['profile'] = $this->profile
;
640 foreach ( $this->namespaces
as $n ) {
645 return $opt +
$this->extraParams
;
649 * Save namespace preferences when we're supposed to
651 * @return bool Whether we wrote something
653 protected function saveNamespaces() {
654 $user = $this->getUser();
655 $request = $this->getRequest();
657 if ( $user->isLoggedIn() &&
658 $user->matchEditToken(
659 $request->getVal( 'nsRemember' ),
664 // Reset namespace preferences: namespaces are not searched
665 // when they're not mentioned in the URL parameters.
666 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
667 $user->setOption( 'searchNs' . $n, false );
669 // The request parameters include all the namespaces to be searched.
670 // Even if they're the same as an existing profile, they're not eaten.
671 foreach ( $this->namespaces
as $n ) {
672 $user->setOption( 'searchNs' . $n, true );
675 $user->saveSettings();
683 * Show whole set of results
685 * @param SearchResultSet $matches
686 * @param string $interwiki Interwiki name
690 protected function showMatches( &$matches, $interwiki = null ) {
693 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
695 $result = $matches->next();
696 $pos = $this->offset
;
698 if ( $result && $interwiki ) {
699 $out .= $this->interwikiHeader( $interwiki, $result );
702 $out .= "<ul class='mw-search-results'>\n";
704 $out .= $this->showHit( $result, $terms, ++
$pos );
705 $result = $matches->next();
709 // convert the whole thing to desired language variant
710 $out = $wgContLang->convert( $out );
716 * Format a single hit result
718 * @param SearchResult $result
719 * @param array $terms Terms to highlight
720 * @param int $position Position within the search results, including offset.
724 protected function showHit( $result, $terms, $position ) {
726 if ( $result->isBrokenTitle() ) {
730 $title = $result->getTitle();
732 $titleSnippet = $result->getTitleSnippet();
734 if ( $titleSnippet == '' ) {
735 $titleSnippet = null;
738 $link_t = clone $title;
741 Hooks
::run( 'ShowSearchHitTitle',
742 [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
744 $link = Linker
::linkKnown(
747 [ 'data-serp-pos' => $position ], // HTML attributes
751 // If page content is not readable, just return the title.
752 // This is not quite safe, but better than showing excerpts from non-readable pages
753 // Note that hiding the entry entirely would screw up paging.
754 if ( !$title->userCan( 'read', $this->getUser() ) ) {
755 return "<li>{$link}</li>\n";
758 // If the page doesn't *exist*... our search index is out of date.
759 // The least confusing at this point is to drop the result.
760 // You may get less results, but... oh well. :P
761 if ( $result->isMissingRevision() ) {
765 // format redirects / relevant sections
766 $redirectTitle = $result->getRedirectTitle();
767 $redirectText = $result->getRedirectSnippet();
768 $sectionTitle = $result->getSectionTitle();
769 $sectionText = $result->getSectionSnippet();
770 $categorySnippet = $result->getCategorySnippet();
773 if ( !is_null( $redirectTitle ) ) {
774 if ( $redirectText == '' ) {
775 $redirectText = null;
778 $redirect = "<span class='searchalttitle'>" .
779 $this->msg( 'search-redirect' )->rawParams(
780 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
785 if ( !is_null( $sectionTitle ) ) {
786 if ( $sectionText == '' ) {
790 $section = "<span class='searchalttitle'>" .
791 $this->msg( 'search-section' )->rawParams(
792 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
797 if ( $categorySnippet ) {
798 $category = "<span class='searchalttitle'>" .
799 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
803 // format text extract
804 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
806 $lang = $this->getLanguage();
808 // format description
809 $byteSize = $result->getByteSize();
810 $wordCount = $result->getWordCount();
811 $timestamp = $result->getTimestamp();
812 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
813 ->numParams( $wordCount )->escaped();
815 if ( $title->getNamespace() == NS_CATEGORY
) {
816 $cat = Category
::newFromTitle( $title );
817 $size = $this->msg( 'search-result-category-size' )
818 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
822 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
825 // Include a thumbnail for media files...
826 if ( $title->getNamespace() == NS_FILE
) {
827 $img = $result->getFile();
828 $img = $img ?
: wfFindFile( $title );
829 if ( $result->isFileMatch() ) {
830 $fileMatch = "<span class='searchalttitle'>" .
831 $this->msg( 'search-file-match' )->escaped() . "</span>";
834 $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
836 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
837 // Float doesn't seem to interact well with the bullets.
838 // Table messes up vertical alignment of the bullets.
839 // Bullets are therefore disabled (didn't look great anyway).
841 '<table class="searchResultImage">' .
843 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
844 $thumb->toHtml( [ 'desc-link' => true ] ) .
846 '<td style="vertical-align: top;">' .
847 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
849 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
862 if ( Hooks
::run( 'ShowSearchHit', [
863 $this, $result, $terms,
864 &$link, &$redirect, &$section, &$extract,
865 &$score, &$size, &$date, &$related,
868 $html = "<li><div class='mw-search-result-heading'>" .
869 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
870 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
878 * Extract custom captions from search-interwiki-custom message
880 protected function getCustomCaptions() {
881 if ( is_null( $this->customCaptions
) ) {
882 $this->customCaptions
= [];
883 // format per line <iwprefix>:<caption>
884 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
885 foreach ( $customLines as $line ) {
886 $parts = explode( ":", $line, 2 );
887 if ( count( $parts ) == 2 ) { // validate line
888 $this->customCaptions
[$parts[0]] = $parts[1];
895 * Show results from other wikis
897 * @param SearchResultSet|array $matches
898 * @param string $query
902 protected function showInterwiki( $matches, $query ) {
905 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
906 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
907 $out .= "<ul class='mw-search-iwresults'>\n";
909 // work out custom project captions
910 $this->getCustomCaptions();
912 if ( !is_array( $matches ) ) {
913 $matches = [ $matches ];
916 foreach ( $matches as $set ) {
918 $result = $set->next();
920 $out .= $this->showInterwikiHit( $result, $prev, $query );
921 $prev = $result->getInterwikiPrefix();
922 $result = $set->next();
926 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
927 $out .= "</ul></div>\n";
929 // convert the whole thing to desired language variant
930 $out = $wgContLang->convert( $out );
936 * Show single interwiki link
938 * @param SearchResult $result
939 * @param string $lastInterwiki
940 * @param string $query
944 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
946 if ( $result->isBrokenTitle() ) {
950 $title = $result->getTitle();
952 $titleSnippet = $result->getTitleSnippet();
954 if ( $titleSnippet == '' ) {
955 $titleSnippet = null;
958 $link = Linker
::linkKnown(
963 // format redirect if any
964 $redirectTitle = $result->getRedirectTitle();
965 $redirectText = $result->getRedirectSnippet();
967 if ( !is_null( $redirectTitle ) ) {
968 if ( $redirectText == '' ) {
969 $redirectText = null;
972 $redirect = "<span class='searchalttitle'>" .
973 $this->msg( 'search-redirect' )->rawParams(
974 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
979 // display project name
980 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
981 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions
) ) {
982 // captions from 'search-interwiki-custom'
983 $caption = $this->customCaptions
[$title->getInterwiki()];
985 // default is to show the hostname of the other wiki which might suck
986 // if there are many wikis on one hostname
987 $parsed = wfParseUrl( $title->getFullURL() );
988 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
990 // "more results" link (special page stuff could be localized, but we might not know target lang)
991 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
992 $searchLink = Linker
::linkKnown(
994 $this->msg( 'search-interwiki-more' )->text(),
998 'fulltext' => 'Search'
1001 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1002 {$searchLink}</span>{$caption}</div>\n<ul>";
1005 $out .= "<li>{$link} {$redirect}</li>\n";
1011 * Generates the power search box at [[Special:Search]]
1013 * @param string $term Search term
1014 * @param array $opts
1015 * @return string HTML form
1017 protected function powerSearchBox( $term, $opts ) {
1020 // Groups namespaces into rows according to subject
1022 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
1023 $subject = MWNamespace
::getSubject( $namespace );
1024 if ( !array_key_exists( $subject, $rows ) ) {
1025 $rows[$subject] = "";
1028 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1029 if ( $name == '' ) {
1030 $name = $this->msg( 'blanknamespace' )->text();
1034 Xml
::openElement( 'td' ) .
1038 "mw-search-ns{$namespace}",
1039 in_array( $namespace, $this->namespaces
)
1041 Xml
::closeElement( 'td' );
1044 $rows = array_values( $rows );
1045 $numRows = count( $rows );
1047 // Lays out namespaces in multiple floating two-column tables so they'll
1048 // be arranged nicely while still accommodating different screen widths
1049 $namespaceTables = '';
1050 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
1051 $namespaceTables .= Xml
::openElement( 'table' );
1053 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
1054 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
1057 $namespaceTables .= Xml
::closeElement( 'table' );
1060 $showSections = [ 'namespaceTables' => $namespaceTables ];
1062 Hooks
::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1065 foreach ( $opts as $key => $value ) {
1066 $hidden .= Html
::hidden( $key, $value );
1069 # Stuff to feed saveNamespaces()
1071 $user = $this->getUser();
1072 if ( $user->isLoggedIn() ) {
1073 $remember .= Xml
::checkLabel(
1074 $this->msg( 'powersearch-remember' )->text(),
1076 'mw-search-powersearch-remember',
1078 // The token goes here rather than in a hidden field so it
1079 // is only sent when necessary (not every form submission).
1080 [ 'value' => $user->getEditToken(
1087 // Return final output
1088 return Xml
::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1089 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1090 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1091 Xml
::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1092 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1093 implode( Xml
::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1095 Xml
::element( 'div', [ 'class' => 'divider' ], '', false ) .
1097 Xml
::closeElement( 'fieldset' );
1103 protected function getSearchProfiles() {
1104 // Builds list of Search Types (profiles)
1105 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1109 'message' => 'searchprofile-articles',
1110 'tooltip' => 'searchprofile-articles-tooltip',
1111 'namespaces' => SearchEngine
::defaultNamespaces(),
1112 'namespace-messages' => SearchEngine
::namespacesAsText(
1113 SearchEngine
::defaultNamespaces()
1117 'message' => 'searchprofile-images',
1118 'tooltip' => 'searchprofile-images-tooltip',
1119 'namespaces' => [ NS_FILE
],
1122 'message' => 'searchprofile-everything',
1123 'tooltip' => 'searchprofile-everything-tooltip',
1124 'namespaces' => $nsAllSet,
1127 'message' => 'searchprofile-advanced',
1128 'tooltip' => 'searchprofile-advanced-tooltip',
1129 'namespaces' => self
::NAMESPACES_CURRENT
,
1133 Hooks
::run( 'SpecialSearchProfiles', [ &$profiles ] );
1135 foreach ( $profiles as &$data ) {
1136 if ( !is_array( $data['namespaces'] ) ) {
1139 sort( $data['namespaces'] );
1146 * @param string $term
1149 protected function searchProfileTabs( $term ) {
1150 $out = Xml
::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1153 if ( $this->startsWithImage( $term ) ) {
1155 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1158 $profiles = $this->getSearchProfiles();
1159 $lang = $this->getLanguage();
1161 // Outputs XML for Search Types
1162 $out .= Xml
::openElement( 'div', [ 'class' => 'search-types' ] );
1163 $out .= Xml
::openElement( 'ul' );
1164 foreach ( $profiles as $id => $profile ) {
1165 if ( !isset( $profile['parameters'] ) ) {
1166 $profile['parameters'] = [];
1168 $profile['parameters']['profile'] = $id;
1170 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1171 $lang->commaList( $profile['namespace-messages'] ) : null;
1175 'class' => $this->profile
=== $id ?
'current' : 'normal'
1177 $this->makeSearchLink(
1180 $this->msg( $profile['message'] )->text(),
1181 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1182 $profile['parameters']
1186 $out .= Xml
::closeElement( 'ul' );
1187 $out .= Xml
::closeElement( 'div' );
1188 $out .= Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1189 $out .= Xml
::closeElement( 'div' );
1195 * @param string $term Search term
1198 protected function searchOptions( $term ) {
1201 $opts['profile'] = $this->profile
;
1203 if ( $this->isPowerSearch() ) {
1204 $out .= $this->powerSearchBox( $term, $opts );
1207 Hooks
::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile
, $term, $opts ] );
1215 * @param string $term
1216 * @param int $resultsShown
1217 * @param int $totalNum
1220 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1221 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1222 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1224 $out .= Html
::input( 'search', $term, 'search', [
1225 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1227 'autofocus' => trim( $term ) === '',
1228 'class' => 'mw-ui-input mw-ui-input-inline',
1229 // identifies the location of the search bar for tracking purposes
1230 'data-search-loc' => 'content',
1232 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1233 $out .= Html
::submitButton(
1234 $this->msg( 'searchbutton' )->text(),
1235 [ 'class' => 'mw-ui-button mw-ui-progressive' ],
1236 [ 'mw-ui-progressive' ]
1240 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1241 $top = $this->msg( 'search-showingresults' )
1242 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1243 ->numParams( $resultsShown )
1245 $out .= Xml
::tags( 'div', [ 'class' => 'results-info' ], $top ) .
1246 Xml
::element( 'div', [ 'style' => 'clear:both' ], '', false );
1253 * Make a search link with some target namespaces
1255 * @param string $term
1256 * @param array $namespaces Ignored
1257 * @param string $label Link's text
1258 * @param string $tooltip Link's tooltip
1259 * @param array $params Query string parameters
1260 * @return string HTML fragment
1262 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1264 foreach ( $namespaces as $n ) {
1265 $opt['ns' . $n] = 1;
1268 $stParams = array_merge(
1271 'fulltext' => $this->msg( 'search' )->text()
1276 return Xml
::element(
1279 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1287 * Check if query starts with image: prefix
1289 * @param string $term The string to check
1292 protected function startsWithImage( $term ) {
1295 $parts = explode( ':', $term );
1296 if ( count( $parts ) > 1 ) {
1297 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1304 * Check if query starts with all: prefix
1306 * @param string $term The string to check
1309 protected function startsWithAll( $term ) {
1311 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1313 $parts = explode( ':', $term );
1314 if ( count( $parts ) > 1 ) {
1315 return $parts[0] == $allkeyword;
1324 * @return SearchEngine
1326 public function getSearchEngine() {
1327 if ( $this->searchEngine
=== null ) {
1328 $this->searchEngine
= $this->searchEngineType ?
1329 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1332 return $this->searchEngine
;
1336 * Current search profile.
1337 * @return null|string
1339 function getProfile() {
1340 return $this->profile
;
1344 * Current namespaces.
1347 function getNamespaces() {
1348 return $this->namespaces
;
1352 * Users of hook SpecialSearchSetupEngine can use this to
1353 * add more params to links to not lose selection when
1354 * user navigates search results.
1357 * @param string $key
1358 * @param mixed $value
1360 public function setExtraParam( $key, $value ) {
1361 $this->extraParams
[$key] = $value;
1364 protected function getGroupName() {