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 = array();
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;
76 const NAMESPACES_CURRENT
= 'sense';
78 public function __construct() {
79 parent
::__construct( 'Search' );
87 public function execute( $par ) {
89 $this->outputHeader();
90 $out = $this->getOutput();
91 $out->allowClickjacking();
92 $out->addModuleStyles( array(
93 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
97 // Strip underscores from title parameter; most of the time we'll want
98 // text form here. But don't strip underscores from actual text params!
99 $titleParam = str_replace( '_', ' ', $par );
101 $request = $this->getRequest();
103 // Fetch the search term
104 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
107 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
108 $this->saveNamespaces();
109 // Remove the token from the URL to prevent the user from inadvertently
110 // exposing it (e.g. by pasting it into a public wiki page) or undoing
111 // later settings changes (e.g. by reloading the page).
112 $query = $request->getValues();
113 unset( $query['title'], $query['nsRemember'] );
114 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
118 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
119 $this->searchEngineType
= $request->getVal( 'srbackend' );
121 if ( $request->getVal( 'fulltext' )
122 ||
!is_null( $request->getVal( 'offset' ) )
124 $this->showResults( $search );
126 $this->goResult( $search );
131 * Set up basic search parameters from the request and user settings.
133 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
135 public function load() {
136 $request = $this->getRequest();
137 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
138 $this->mPrefix
= $request->getVal( 'prefix', '' );
140 $user = $this->getUser();
142 # Extract manually requested namespaces
143 $nslist = $this->powerSearch( $request );
144 if ( !count( $nslist ) ) {
145 # Fallback to user preference
146 $nslist = SearchEngine
::userNamespaces( $user );
150 if ( !count( $nslist ) ) {
151 $profile = 'default';
154 $profile = $request->getVal( 'profile', $profile );
155 $profiles = $this->getSearchProfiles();
156 if ( $profile === null ) {
157 // BC with old request format
158 $profile = 'advanced';
159 foreach ( $profiles as $key => $data ) {
160 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
164 $this->namespaces
= $nslist;
165 } elseif ( $profile === 'advanced' ) {
166 $this->namespaces
= $nslist;
168 if ( isset( $profiles[$profile]['namespaces'] ) ) {
169 $this->namespaces
= $profiles[$profile]['namespaces'];
171 // Unknown profile requested
172 $profile = 'default';
173 $this->namespaces
= $profiles['default']['namespaces'];
177 $this->fulltext
= $request->getVal( 'fulltext' );
178 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
179 $this->profile
= $profile;
183 * If an exact title match can be found, jump straight ahead to it.
185 * @param string $term
187 public function goResult( $term ) {
188 $this->setupPage( $term );
189 # Try to go to page as entered.
190 $title = Title
::newFromText( $term );
191 # If the string cannot be used to create a title
192 if ( is_null( $title ) ) {
193 $this->showResults( $term );
197 # If there's an exact or very near match, jump right there.
198 $title = SearchEngine
::getNearMatch( $term );
200 if ( !is_null( $title ) ) {
201 $this->getOutput()->redirect( $title->getFullURL() );
205 # No match, generate an edit URL
206 $title = Title
::newFromText( $term );
207 if ( !is_null( $title ) ) {
208 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
210 $this->showResults( $term );
214 * @param string $term
216 public function showResults( $term ) {
219 $search = $this->getSearchEngine();
220 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
221 $search->setLimitOffset( $this->limit
, $this->offset
);
222 $search->setNamespaces( $this->namespaces
);
223 $search->prefix
= $this->mPrefix
;
224 $term = $search->transformSearchTerm( $term );
226 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
228 $this->setupPage( $term );
230 $out = $this->getOutput();
232 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
233 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
234 if ( $searchFowardUrl ) {
235 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
236 $out->redirect( $url );
239 Xml
::openElement( 'fieldset' ) .
240 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
243 array( 'class' => 'mw-searchdisabled' ),
244 $this->msg( 'searchdisabled' )->text()
246 $this->msg( 'googlesearch' )->rawParams(
247 htmlspecialchars( $term ),
249 $this->msg( 'searchbutton' )->escaped()
251 Xml
::closeElement( 'fieldset' )
258 $title = Title
::newFromText( $term );
259 $showSuggestion = $title === null ||
!$title->isKnown();
260 $search->setShowSuggestion( $showSuggestion );
262 // fetch search results
263 $rewritten = $search->replacePrefixes( $term );
265 $titleMatches = $search->searchTitle( $rewritten );
266 $textMatches = $search->searchText( $rewritten );
269 if ( $textMatches instanceof Status
) {
270 $textStatus = $textMatches;
274 // did you mean... suggestions
275 $didYouMeanHtml = '';
276 if ( $showSuggestion && $textMatches && !$textStatus ) {
277 if ( $textMatches->hasRewrittenQuery() ) {
278 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
279 } elseif ( $textMatches->hasSuggestion() ) {
280 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
284 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
285 # Hook requested termination
289 // start rendering the page
294 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
296 'action' => wfScript(),
301 // Get number of results
302 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
303 if ( $titleMatches ) {
304 $titleMatchesNum = $titleMatches->numRows();
305 $numTitleMatches = $titleMatches->getTotalHits();
307 if ( $textMatches ) {
308 $textMatchesNum = $textMatches->numRows();
309 $numTextMatches = $textMatches->getTotalHits();
311 $num = $titleMatchesNum +
$textMatchesNum;
312 $totalRes = $numTitleMatches +
$numTextMatches;
315 # This is an awful awful ID name. It's not a table, but we
316 # named it poorly from when this was a table so now we're
318 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
319 $this->shortDialog( $term, $num, $totalRes ) .
320 Xml
::closeElement( 'div' ) .
321 $this->searchProfileTabs( $term ) .
322 $this->searchOptions( $term ) .
323 Xml
::closeElement( 'form' ) .
327 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
328 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
329 // Empty query -- straight view of search form
333 $out->addHtml( "<div class='searchresults'>" );
337 if ( $num ||
$this->offset
) {
338 // Show the create link ahead
339 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
340 if ( $totalRes > $this->limit ||
$this->offset
) {
341 if ( $this->searchEngineType
!== null ) {
342 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
344 $prevnext = $this->getLanguage()->viewPrevNext(
345 $this->getPageTitle(),
348 $this->powerSearchOptions() +
array( 'search' => $term ),
349 $this->limit +
$this->offset
>= $totalRes
353 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
355 $out->parserOptions()->setEditSection( false );
356 if ( $titleMatches ) {
357 if ( $numTitleMatches > 0 ) {
358 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
359 $out->addHTML( $this->showMatches( $titleMatches ) );
361 $titleMatches->free();
363 if ( $textMatches && !$textStatus ) {
364 // output appropriate heading
365 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
366 // if no title matches the heading is redundant
367 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
371 if ( $numTextMatches > 0 ) {
372 $out->addHTML( $this->showMatches( $textMatches ) );
374 // show interwiki results if any
375 if ( $textMatches->hasInterwikiResults() ) {
376 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
379 $textMatches->free();
383 $out->addHTML( '<div class="error">' .
384 $textStatus->getMessage( 'search-error' ) . '</div>' );
386 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
387 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
388 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
392 $out->addHTML( '<div class="visualClear"></div>' );
394 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
397 $out->addHtml( "</div>" );
399 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
404 * Decide if the suggested query should be run, and it's results returned
405 * instead of the provided $textMatches
407 * @param SearchResultSet $textMatches The results of a users query
410 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
411 if ( !$this->runSuggestion ||
412 !$textMatches->hasSuggestion() ||
413 $textMatches->numRows() > 0 ||
414 $textMatches->searchContainedSyntax()
419 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
423 * Generates HTML shown to the user when we have a suggestion about a query
424 * that might give more results than their current query.
426 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
427 # mirror Go/Search behavior of original request ..
428 $params = array( 'search' => $textMatches->getSuggestionQuery() );
429 if ( $this->fulltext
!= null ) {
430 $params['fulltext'] = $this->fulltext
;
432 $stParams = array_merge( $params, $this->powerSearchOptions() );
434 $suggest = Linker
::linkKnown(
435 $this->getPageTitle(),
436 $textMatches->getSuggestionSnippet() ?
: null,
437 array( 'id' => 'mw-search-DYM-suggestion' ),
441 # HTML of did you mean... search suggestion link
442 return Html
::rawElement(
444 array( 'class' => 'searchdidyoumean' ),
445 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
450 * Generates HTML shown to user when their query has been internally rewritten,
451 * and the results of the rewritten query are being returned.
453 * @param string $term The users search input
454 * @param SearchResultSet $textMatches The response to the users initial search request
455 * @return string HTML linking the user to their original $term query, and the one
456 * suggested by $textMatches.
458 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
459 // Showing results for '$rewritten'
460 // Search instead for '$orig'
462 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
463 if ( $this->fulltext
!= null ) {
464 $params['fulltext'] = $this->fulltext
;
466 $stParams = array_merge( $params, $this->powerSearchOptions() );
468 $rewritten = Linker
::linkKnown(
469 $this->getPageTitle(),
470 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
471 array( 'id' => 'mw-search-DYM-rewritten' ),
475 $stParams['search'] = $term;
476 $stParams['runsuggestion'] = 0;
477 $original = Linker
::linkKnown(
478 $this->getPageTitle(),
479 htmlspecialchars( $term ),
480 array( 'id' => 'mw-search-DYM-original' ),
484 return Html
::rawElement(
486 array( 'class' => 'searchdidyoumean' ),
487 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
492 * @param Title $title
493 * @param int $num The number of search results found
494 * @param null|SearchResultSet $titleMatches Results from title search
495 * @param null|SearchResultSet $textMatches Results from text search
497 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
498 // show direct page/create link if applicable
500 // Check DBkey !== '' in case of fragment link only.
501 if ( is_null( $title ) ||
$title->getDBkey() === ''
502 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
503 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
506 // preserve the paragraph for margins etc...
507 $this->getOutput()->addHtml( '<p></p>' );
512 $messageName = 'searchmenu-new-nocreate';
513 $linkClass = 'mw-search-createlink';
515 if ( !$title->isExternal() ) {
516 if ( $title->isKnown() ) {
517 $messageName = 'searchmenu-exists';
518 $linkClass = 'mw-search-exists';
519 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
520 $messageName = 'searchmenu-new';
526 wfEscapeWikiText( $title->getPrefixedText() ),
527 Message
::numParam( $num )
529 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
531 // Extensions using the hook might still return an empty $messageName
532 if ( $messageName ) {
533 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
535 // preserve the paragraph for margins etc...
536 $this->getOutput()->addHtml( '<p></p>' );
541 * @param string $term
543 protected function setupPage( $term ) {
544 $out = $this->getOutput();
545 if ( strval( $term ) !== '' ) {
546 $out->setPageTitle( $this->msg( 'searchresults' ) );
547 $out->setHTMLTitle( $this->msg( 'pagetitle' )
548 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
549 ->inContentLanguage()->text()
552 // add javascript specific to special:search
553 $out->addModules( 'mediawiki.special.search' );
557 * Return true if current search is a power (advanced) search
561 protected function isPowerSearch() {
562 return $this->profile
=== 'advanced';
566 * Extract "power search" namespace settings from the request object,
567 * returning a list of index numbers to search.
569 * @param WebRequest $request
572 protected function powerSearch( &$request ) {
574 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
575 if ( $request->getCheck( 'ns' . $ns ) ) {
584 * Reconstruct the 'power search' options for links
588 protected function powerSearchOptions() {
590 if ( !$this->isPowerSearch() ) {
591 $opt['profile'] = $this->profile
;
593 foreach ( $this->namespaces
as $n ) {
598 return $opt +
$this->extraParams
;
602 * Save namespace preferences when we're supposed to
604 * @return bool Whether we wrote something
606 protected function saveNamespaces() {
607 $user = $this->getUser();
608 $request = $this->getRequest();
610 if ( $user->isLoggedIn() &&
611 $user->matchEditToken(
612 $request->getVal( 'nsRemember' ),
617 // Reset namespace preferences: namespaces are not searched
618 // when they're not mentioned in the URL parameters.
619 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
620 $user->setOption( 'searchNs' . $n, false );
622 // The request parameters include all the namespaces to be searched.
623 // Even if they're the same as an existing profile, they're not eaten.
624 foreach ( $this->namespaces
as $n ) {
625 $user->setOption( 'searchNs' . $n, true );
628 $user->saveSettings();
636 * Show whole set of results
638 * @param SearchResultSet $matches
642 protected function showMatches( &$matches ) {
645 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
647 $out = "<ul class='mw-search-results'>\n";
648 $result = $matches->next();
649 $pos = $this->offset
;
651 $out .= $this->showHit( $result, $terms, ++
$pos );
652 $result = $matches->next();
656 // convert the whole thing to desired language variant
657 $out = $wgContLang->convert( $out );
663 * Format a single hit result
665 * @param SearchResult $result
666 * @param array $terms Terms to highlight
667 * @param int $position Position within the search results, including offset.
671 protected function showHit( $result, $terms, $position ) {
673 if ( $result->isBrokenTitle() ) {
677 $title = $result->getTitle();
679 $titleSnippet = $result->getTitleSnippet();
681 if ( $titleSnippet == '' ) {
682 $titleSnippet = null;
685 $link_t = clone $title;
687 Hooks
::run( 'ShowSearchHitTitle',
688 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
690 $link = Linker
::linkKnown(
693 array( 'data-serp-pos' => $position ) // HTML attributes
696 // If page content is not readable, just return the title.
697 // This is not quite safe, but better than showing excerpts from non-readable pages
698 // Note that hiding the entry entirely would screw up paging.
699 if ( !$title->userCan( 'read', $this->getUser() ) ) {
700 return "<li>{$link}</li>\n";
703 // If the page doesn't *exist*... our search index is out of date.
704 // The least confusing at this point is to drop the result.
705 // You may get less results, but... oh well. :P
706 if ( $result->isMissingRevision() ) {
710 // format redirects / relevant sections
711 $redirectTitle = $result->getRedirectTitle();
712 $redirectText = $result->getRedirectSnippet();
713 $sectionTitle = $result->getSectionTitle();
714 $sectionText = $result->getSectionSnippet();
715 $categorySnippet = $result->getCategorySnippet();
718 if ( !is_null( $redirectTitle ) ) {
719 if ( $redirectText == '' ) {
720 $redirectText = null;
723 $redirect = "<span class='searchalttitle'>" .
724 $this->msg( 'search-redirect' )->rawParams(
725 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
730 if ( !is_null( $sectionTitle ) ) {
731 if ( $sectionText == '' ) {
735 $section = "<span class='searchalttitle'>" .
736 $this->msg( 'search-section' )->rawParams(
737 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
742 if ( $categorySnippet ) {
743 $category = "<span class='searchalttitle'>" .
744 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
748 // format text extract
749 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
751 $lang = $this->getLanguage();
753 // format description
754 $byteSize = $result->getByteSize();
755 $wordCount = $result->getWordCount();
756 $timestamp = $result->getTimestamp();
757 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
758 ->numParams( $wordCount )->escaped();
760 if ( $title->getNamespace() == NS_CATEGORY
) {
761 $cat = Category
::newFromTitle( $title );
762 $size = $this->msg( 'search-result-category-size' )
763 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
767 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
770 // Include a thumbnail for media files...
771 if ( $title->getNamespace() == NS_FILE
) {
772 $img = $result->getFile();
773 $img = $img ?
: wfFindFile( $title );
774 if ( $result->isFileMatch() ) {
775 $fileMatch = "<span class='searchalttitle'>" .
776 $this->msg( 'search-file-match' )->escaped() . "</span>";
779 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
781 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
782 // Float doesn't seem to interact well with the bullets.
783 // Table messes up vertical alignment of the bullets.
784 // Bullets are therefore disabled (didn't look great anyway).
786 '<table class="searchResultImage">' .
788 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
789 $thumb->toHtml( array( 'desc-link' => true ) ) .
791 '<td style="vertical-align: top;">' .
792 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
794 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
806 if ( Hooks
::run( 'ShowSearchHit', array(
807 $this, $result, $terms,
808 &$link, &$redirect, &$section, &$extract,
809 &$score, &$size, &$date, &$related,
812 $html = "<li><div class='mw-search-result-heading'>" .
813 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
814 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
822 * Show results from other wikis
824 * @param SearchResultSet|array $matches
825 * @param string $query
829 protected function showInterwiki( $matches, $query ) {
832 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
833 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
834 $out .= "<ul class='mw-search-iwresults'>\n";
836 // work out custom project captions
837 $customCaptions = array();
838 // format per line <iwprefix>:<caption>
839 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
840 foreach ( $customLines as $line ) {
841 $parts = explode( ":", $line, 2 );
842 if ( count( $parts ) == 2 ) { // validate line
843 $customCaptions[$parts[0]] = $parts[1];
847 if ( !is_array( $matches ) ) {
848 $matches = array( $matches );
851 foreach ( $matches as $set ) {
853 $result = $set->next();
855 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
856 $prev = $result->getInterwikiPrefix();
857 $result = $set->next();
861 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
862 $out .= "</ul></div>\n";
864 // convert the whole thing to desired language variant
865 $out = $wgContLang->convert( $out );
871 * Show single interwiki link
873 * @param SearchResult $result
874 * @param string $lastInterwiki
875 * @param string $query
876 * @param array $customCaptions Interwiki prefix -> caption
880 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
882 if ( $result->isBrokenTitle() ) {
886 $title = $result->getTitle();
888 $titleSnippet = $result->getTitleSnippet();
890 if ( $titleSnippet == '' ) {
891 $titleSnippet = null;
894 $link = Linker
::linkKnown(
899 // format redirect if any
900 $redirectTitle = $result->getRedirectTitle();
901 $redirectText = $result->getRedirectSnippet();
903 if ( !is_null( $redirectTitle ) ) {
904 if ( $redirectText == '' ) {
905 $redirectText = null;
908 $redirect = "<span class='searchalttitle'>" .
909 $this->msg( 'search-redirect' )->rawParams(
910 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
915 // display project name
916 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
917 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
918 // captions from 'search-interwiki-custom'
919 $caption = $customCaptions[$title->getInterwiki()];
921 // default is to show the hostname of the other wiki which might suck
922 // if there are many wikis on one hostname
923 $parsed = wfParseUrl( $title->getFullURL() );
924 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
926 // "more results" link (special page stuff could be localized, but we might not know target lang)
927 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
928 $searchLink = Linker
::linkKnown(
930 $this->msg( 'search-interwiki-more' )->text(),
934 'fulltext' => 'Search'
937 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
938 {$searchLink}</span>{$caption}</div>\n<ul>";
941 $out .= "<li>{$link} {$redirect}</li>\n";
947 * Generates the power search box at [[Special:Search]]
949 * @param string $term Search term
951 * @return string HTML form
953 protected function powerSearchBox( $term, $opts ) {
956 // Groups namespaces into rows according to subject
958 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
959 $subject = MWNamespace
::getSubject( $namespace );
960 if ( !array_key_exists( $subject, $rows ) ) {
961 $rows[$subject] = "";
964 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
966 $name = $this->msg( 'blanknamespace' )->text();
970 Xml
::openElement( 'td' ) .
974 "mw-search-ns{$namespace}",
975 in_array( $namespace, $this->namespaces
)
977 Xml
::closeElement( 'td' );
980 $rows = array_values( $rows );
981 $numRows = count( $rows );
983 // Lays out namespaces in multiple floating two-column tables so they'll
984 // be arranged nicely while still accommodating different screen widths
985 $namespaceTables = '';
986 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
987 $namespaceTables .= Xml
::openElement( 'table' );
989 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
990 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
993 $namespaceTables .= Xml
::closeElement( 'table' );
996 $showSections = array( 'namespaceTables' => $namespaceTables );
998 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1001 foreach ( $opts as $key => $value ) {
1002 $hidden .= Html
::hidden( $key, $value );
1005 # Stuff to feed saveNamespaces()
1007 $user = $this->getUser();
1008 if ( $user->isLoggedIn() ) {
1009 $remember .= Xml
::checkLabel(
1010 $this->msg( 'powersearch-remember' )->text(),
1012 'mw-search-powersearch-remember',
1014 // The token goes here rather than in a hidden field so it
1015 // is only sent when necessary (not every form submission).
1016 array( 'value' => $user->getEditToken(
1023 // Return final output
1024 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1025 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1026 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1027 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1028 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1029 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1031 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1033 Xml
::closeElement( 'fieldset' );
1039 protected function getSearchProfiles() {
1040 // Builds list of Search Types (profiles)
1041 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1045 'message' => 'searchprofile-articles',
1046 'tooltip' => 'searchprofile-articles-tooltip',
1047 'namespaces' => SearchEngine
::defaultNamespaces(),
1048 'namespace-messages' => SearchEngine
::namespacesAsText(
1049 SearchEngine
::defaultNamespaces()
1053 'message' => 'searchprofile-images',
1054 'tooltip' => 'searchprofile-images-tooltip',
1055 'namespaces' => array( NS_FILE
),
1058 'message' => 'searchprofile-everything',
1059 'tooltip' => 'searchprofile-everything-tooltip',
1060 'namespaces' => $nsAllSet,
1062 'advanced' => array(
1063 'message' => 'searchprofile-advanced',
1064 'tooltip' => 'searchprofile-advanced-tooltip',
1065 'namespaces' => self
::NAMESPACES_CURRENT
,
1069 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1071 foreach ( $profiles as &$data ) {
1072 if ( !is_array( $data['namespaces'] ) ) {
1075 sort( $data['namespaces'] );
1082 * @param string $term
1085 protected function searchProfileTabs( $term ) {
1086 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1089 if ( $this->startsWithImage( $term ) ) {
1091 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1094 $profiles = $this->getSearchProfiles();
1095 $lang = $this->getLanguage();
1097 // Outputs XML for Search Types
1098 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1099 $out .= Xml
::openElement( 'ul' );
1100 foreach ( $profiles as $id => $profile ) {
1101 if ( !isset( $profile['parameters'] ) ) {
1102 $profile['parameters'] = array();
1104 $profile['parameters']['profile'] = $id;
1106 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1107 $lang->commaList( $profile['namespace-messages'] ) : null;
1111 'class' => $this->profile
=== $id ?
'current' : 'normal'
1113 $this->makeSearchLink(
1116 $this->msg( $profile['message'] )->text(),
1117 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1118 $profile['parameters']
1122 $out .= Xml
::closeElement( 'ul' );
1123 $out .= Xml
::closeElement( 'div' );
1124 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1125 $out .= Xml
::closeElement( 'div' );
1131 * @param string $term Search term
1134 protected function searchOptions( $term ) {
1137 $opts['profile'] = $this->profile
;
1139 if ( $this->isPowerSearch() ) {
1140 $out .= $this->powerSearchBox( $term, $opts );
1143 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1151 * @param string $term
1152 * @param int $resultsShown
1153 * @param int $totalNum
1156 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1157 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1158 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1160 $out .= Html
::input( 'search', $term, 'search', array(
1161 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1163 'autofocus' => trim( $term ) === '',
1164 'class' => 'mw-ui-input mw-ui-input-inline',
1166 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1167 $out .= Html
::submitButton(
1168 $this->msg( 'searchbutton' )->text(),
1169 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1170 array( 'mw-ui-progressive' )
1174 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1175 $top = $this->msg( 'search-showingresults' )
1176 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1177 ->numParams( $resultsShown )
1179 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1180 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1187 * Make a search link with some target namespaces
1189 * @param string $term
1190 * @param array $namespaces Ignored
1191 * @param string $label Link's text
1192 * @param string $tooltip Link's tooltip
1193 * @param array $params Query string parameters
1194 * @return string HTML fragment
1196 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1198 foreach ( $namespaces as $n ) {
1199 $opt['ns' . $n] = 1;
1202 $stParams = array_merge(
1205 'fulltext' => $this->msg( 'search' )->text()
1210 return Xml
::element(
1213 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1221 * Check if query starts with image: prefix
1223 * @param string $term The string to check
1226 protected function startsWithImage( $term ) {
1229 $parts = explode( ':', $term );
1230 if ( count( $parts ) > 1 ) {
1231 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1238 * Check if query starts with all: prefix
1240 * @param string $term The string to check
1243 protected function startsWithAll( $term ) {
1245 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1247 $parts = explode( ':', $term );
1248 if ( count( $parts ) > 1 ) {
1249 return $parts[0] == $allkeyword;
1258 * @return SearchEngine
1260 public function getSearchEngine() {
1261 if ( $this->searchEngine
=== null ) {
1262 $this->searchEngine
= $this->searchEngineType ?
1263 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1266 return $this->searchEngine
;
1270 * Current search profile.
1271 * @return null|string
1273 function getProfile() {
1274 return $this->profile
;
1278 * Current namespaces.
1281 function getNamespaces() {
1282 return $this->namespaces
;
1286 * Users of hook SpecialSearchSetupEngine can use this to
1287 * add more params to links to not lose selection when
1288 * user navigates search results.
1291 * @param string $key
1292 * @param mixed $value
1294 public function setExtraParam( $key, $value ) {
1295 $this->extraParams
[$key] = $value;
1298 protected function getGroupName() {