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 $this->searchEngineType
= $request->getVal( 'srbackend' );
120 if ( $request->getVal( 'fulltext' )
121 ||
!is_null( $request->getVal( 'offset' ) )
123 $this->showResults( $search );
125 $this->goResult( $search );
130 * Set up basic search parameters from the request and user settings.
132 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
134 public function load() {
135 $request = $this->getRequest();
136 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
137 $this->mPrefix
= $request->getVal( 'prefix', '' );
139 $user = $this->getUser();
141 # Extract manually requested namespaces
142 $nslist = $this->powerSearch( $request );
143 if ( !count( $nslist ) ) {
144 # Fallback to user preference
145 $nslist = SearchEngine
::userNamespaces( $user );
149 if ( !count( $nslist ) ) {
150 $profile = 'default';
153 $profile = $request->getVal( 'profile', $profile );
154 $profiles = $this->getSearchProfiles();
155 if ( $profile === null ) {
156 // BC with old request format
157 $profile = 'advanced';
158 foreach ( $profiles as $key => $data ) {
159 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
163 $this->namespaces
= $nslist;
164 } elseif ( $profile === 'advanced' ) {
165 $this->namespaces
= $nslist;
167 if ( isset( $profiles[$profile]['namespaces'] ) ) {
168 $this->namespaces
= $profiles[$profile]['namespaces'];
170 // Unknown profile requested
171 $profile = 'default';
172 $this->namespaces
= $profiles['default']['namespaces'];
176 $this->fulltext
= $request->getVal( 'fulltext' );
177 $this->runSuggestion
= (bool)$request->getVal( 'runsuggestion', true );
178 $this->profile
= $profile;
182 * If an exact title match can be found, jump straight ahead to it.
184 * @param string $term
186 public function goResult( $term ) {
187 $this->setupPage( $term );
188 # Try to go to page as entered.
189 $title = Title
::newFromText( $term );
190 # If the string cannot be used to create a title
191 if ( is_null( $title ) ) {
192 $this->showResults( $term );
196 # If there's an exact or very near match, jump right there.
197 $title = SearchEngine
::getNearMatch( $term );
199 if ( !is_null( $title ) ) {
200 $this->getOutput()->redirect( $title->getFullURL() );
204 # No match, generate an edit URL
205 $title = Title
::newFromText( $term );
206 if ( !is_null( $title ) ) {
207 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
209 $this->showResults( $term );
213 * @param string $term
215 public function showResults( $term ) {
218 $search = $this->getSearchEngine();
219 $search->setFeatureData( 'rewrite', $this->runSuggestion
);
220 $search->setLimitOffset( $this->limit
, $this->offset
);
221 $search->setNamespaces( $this->namespaces
);
222 $search->prefix
= $this->mPrefix
;
223 $term = $search->transformSearchTerm( $term );
225 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
227 $this->setupPage( $term );
229 $out = $this->getOutput();
231 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
232 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
233 if ( $searchFowardUrl ) {
234 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
235 $out->redirect( $url );
238 Xml
::openElement( 'fieldset' ) .
239 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
242 array( 'class' => 'mw-searchdisabled' ),
243 $this->msg( 'searchdisabled' )->text()
245 $this->msg( 'googlesearch' )->rawParams(
246 htmlspecialchars( $term ),
248 $this->msg( 'searchbutton' )->escaped()
250 Xml
::closeElement( 'fieldset' )
257 $title = Title
::newFromText( $term );
258 $showSuggestion = $title === null ||
!$title->isKnown();
259 $search->setShowSuggestion( $showSuggestion );
261 // fetch search results
262 $rewritten = $search->replacePrefixes( $term );
264 $titleMatches = $search->searchTitle( $rewritten );
265 $textMatches = $search->searchText( $rewritten );
268 if ( $textMatches instanceof Status
) {
269 $textStatus = $textMatches;
273 // did you mean... suggestions
274 $didYouMeanHtml = '';
275 if ( $showSuggestion && $textMatches && !$textStatus ) {
276 if ( $textMatches->hasRewrittenQuery() ) {
277 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
278 } elseif ( $textMatches->hasSuggestion() ) {
279 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
283 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
284 # Hook requested termination
288 // start rendering the page
293 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
295 'action' => wfScript(),
300 // Get number of results
301 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
302 if ( $titleMatches ) {
303 $titleMatchesNum = $titleMatches->numRows();
304 $numTitleMatches = $titleMatches->getTotalHits();
306 if ( $textMatches ) {
307 $textMatchesNum = $textMatches->numRows();
308 $numTextMatches = $textMatches->getTotalHits();
310 $num = $titleMatchesNum +
$textMatchesNum;
311 $totalRes = $numTitleMatches +
$numTextMatches;
314 # This is an awful awful ID name. It's not a table, but we
315 # named it poorly from when this was a table so now we're
317 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
318 $this->shortDialog( $term, $num, $totalRes ) .
319 Xml
::closeElement( 'div' ) .
320 $this->searchProfileTabs( $term ) .
321 $this->searchOptions( $term ) .
322 Xml
::closeElement( 'form' ) .
326 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
327 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
328 // Empty query -- straight view of search form
332 $out->addHtml( "<div class='searchresults'>" );
336 if ( $num ||
$this->offset
) {
337 // Show the create link ahead
338 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
339 if ( $totalRes > $this->limit ||
$this->offset
) {
340 if ( $this->searchEngineType
!== null ) {
341 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
343 $prevnext = $this->getLanguage()->viewPrevNext(
344 $this->getPageTitle(),
347 $this->powerSearchOptions() +
array( 'search' => $term ),
348 $this->limit +
$this->offset
>= $totalRes
352 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
354 $out->parserOptions()->setEditSection( false );
355 if ( $titleMatches ) {
356 if ( $numTitleMatches > 0 ) {
357 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
358 $out->addHTML( $this->showMatches( $titleMatches ) );
360 $titleMatches->free();
362 if ( $textMatches && !$textStatus ) {
363 // output appropriate heading
364 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
365 // if no title matches the heading is redundant
366 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
370 if ( $numTextMatches > 0 ) {
371 $out->addHTML( $this->showMatches( $textMatches ) );
373 // show interwiki results if any
374 if ( $textMatches->hasInterwikiResults() ) {
375 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
378 $textMatches->free();
382 $out->addHTML( '<div class="error">' .
383 $textStatus->getMessage( 'search-error' ) . '</div>' );
385 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
386 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
387 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
391 $out->addHTML( '<div class="visualClear"></div>' );
393 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
396 $out->addHtml( "</div>" );
398 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out ) );
403 * Decide if the suggested query should be run, and it's results returned
404 * instead of the provided $textMatches
406 * @param SearchResultSet $textMatches The results of a users query
409 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
410 if ( !$this->runSuggestion ||
411 !$textMatches->hasSuggestion() ||
412 $textMatches->numRows() > 0 ||
413 $textMatches->searchContainedSyntax()
418 // Generate a random number between 0 and 1. If the
419 // number is less than the desired percentages run it.
420 $rand = rand( 0, getrandmax() ) / getrandmax();
421 return $this->getConfig()->get( 'SearchRunSuggestedQueryPercent' ) > $rand;
425 * Generates HTML shown to the user when we have a suggestion about a query
426 * that might give more results than their current query.
428 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
429 # mirror Go/Search behavior of original request ..
430 $params = array( 'search' => $textMatches->getSuggestionQuery() );
431 if ( $this->fulltext
!= null ) {
432 $params['fulltext'] = $this->fulltext
;
434 $stParams = array_merge( $params, $this->powerSearchOptions() );
436 $suggest = Linker
::linkKnown(
437 $this->getPageTitle(),
438 $textMatches->getSuggestionSnippet() ?
: null,
439 array( 'id' => 'mw-search-DYM-suggestion' ),
443 # html of did you mean... search suggestion link
444 return Html
::rawElement(
446 array( 'class' => 'searchdidyoumean' ),
447 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
452 * Generates HTML shown to user when their query has been internally rewritten,
453 * and the results of the rewritten query are being returned.
455 * @param string $term The users search input
456 * @param SearchResultSet $textMatches The response to the users initial search request
457 * @return string HTML linking the user to their original $term query, and the one
458 * suggested by $textMatches.
460 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
461 // Showing results for '$rewritten'
462 // Search instead for '$orig'
464 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
465 if ( $this->fulltext
!= null ) {
466 $params['fulltext'] = $this->fulltext
;
468 $stParams = array_merge( $params, $this->powerSearchOptions() );
470 $rewritten = Linker
::linkKnown(
471 $this->getPageTitle(),
472 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
473 array( 'id' => 'mw-search-DYM-rewritten' ),
477 $stParams['search'] = $term;
478 $stParams['runsuggestion'] = 0;
479 $original = Linker
::linkKnown(
480 $this->getPageTitle(),
481 htmlspecialchars( $term ),
482 array( 'id' => 'mw-search-DYM-original' ),
486 return Html
::rawElement(
488 array( 'class' => 'searchdidyoumean' ),
489 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
494 * @param Title $title
495 * @param int $num The number of search results found
496 * @param null|SearchResultSet $titleMatches Results from title search
497 * @param null|SearchResultSet $textMatches Results from text search
499 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
500 // show direct page/create link if applicable
502 // Check DBkey !== '' in case of fragment link only.
503 if ( is_null( $title ) ||
$title->getDBkey() === ''
504 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
505 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
508 // preserve the paragraph for margins etc...
509 $this->getOutput()->addHtml( '<p></p>' );
514 $messageName = 'searchmenu-new-nocreate';
515 $linkClass = 'mw-search-createlink';
517 if ( !$title->isExternal() ) {
518 if ( $title->isKnown() ) {
519 $messageName = 'searchmenu-exists';
520 $linkClass = 'mw-search-exists';
521 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
522 $messageName = 'searchmenu-new';
528 wfEscapeWikiText( $title->getPrefixedText() ),
529 Message
::numParam( $num )
531 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
533 // Extensions using the hook might still return an empty $messageName
534 if ( $messageName ) {
535 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
537 // preserve the paragraph for margins etc...
538 $this->getOutput()->addHtml( '<p></p>' );
543 * @param string $term
545 protected function setupPage( $term ) {
546 $out = $this->getOutput();
547 if ( strval( $term ) !== '' ) {
548 $out->setPageTitle( $this->msg( 'searchresults' ) );
549 $out->setHTMLTitle( $this->msg( 'pagetitle' )
550 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
551 ->inContentLanguage()->text()
554 // add javascript specific to special:search
555 $out->addModules( 'mediawiki.special.search' );
559 * Return true if current search is a power (advanced) search
563 protected function isPowerSearch() {
564 return $this->profile
=== 'advanced';
568 * Extract "power search" namespace settings from the request object,
569 * returning a list of index numbers to search.
571 * @param WebRequest $request
574 protected function powerSearch( &$request ) {
576 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
577 if ( $request->getCheck( 'ns' . $ns ) ) {
586 * Reconstruct the 'power search' options for links
590 protected function powerSearchOptions() {
592 if ( !$this->isPowerSearch() ) {
593 $opt['profile'] = $this->profile
;
595 foreach ( $this->namespaces
as $n ) {
600 return $opt +
$this->extraParams
;
604 * Save namespace preferences when we're supposed to
606 * @return bool Whether we wrote something
608 protected function saveNamespaces() {
609 $user = $this->getUser();
610 $request = $this->getRequest();
612 if ( $user->isLoggedIn() &&
613 $user->matchEditToken(
614 $request->getVal( 'nsRemember' ),
619 // Reset namespace preferences: namespaces are not searched
620 // when they're not mentioned in the URL parameters.
621 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
622 $user->setOption( 'searchNs' . $n, false );
624 // The request parameters include all the namespaces to be searched.
625 // Even if they're the same as an existing profile, they're not eaten.
626 foreach ( $this->namespaces
as $n ) {
627 $user->setOption( 'searchNs' . $n, true );
630 $user->saveSettings();
638 * Show whole set of results
640 * @param SearchResultSet $matches
644 protected function showMatches( &$matches ) {
647 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
649 $out = "<ul class='mw-search-results'>\n";
650 $result = $matches->next();
652 $out .= $this->showHit( $result, $terms );
653 $result = $matches->next();
657 // convert the whole thing to desired language variant
658 $out = $wgContLang->convert( $out );
664 * Format a single hit result
666 * @param SearchResult $result
667 * @param array $terms Terms to highlight
671 protected function showHit( $result, $terms ) {
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(
695 //If page content is not readable, just return the title.
696 //This is not quite safe, but better than showing excerpts from non-readable pages
697 //Note that hiding the entry entirely would screw up paging.
698 if ( !$title->userCan( 'read', $this->getUser() ) ) {
699 return "<li>{$link}</li>\n";
702 // If the page doesn't *exist*... our search index is out of date.
703 // The least confusing at this point is to drop the result.
704 // You may get less results, but... oh well. :P
705 if ( $result->isMissingRevision() ) {
709 // format redirects / relevant sections
710 $redirectTitle = $result->getRedirectTitle();
711 $redirectText = $result->getRedirectSnippet();
712 $sectionTitle = $result->getSectionTitle();
713 $sectionText = $result->getSectionSnippet();
714 $categorySnippet = $result->getCategorySnippet();
717 if ( !is_null( $redirectTitle ) ) {
718 if ( $redirectText == '' ) {
719 $redirectText = null;
722 $redirect = "<span class='searchalttitle'>" .
723 $this->msg( 'search-redirect' )->rawParams(
724 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
729 if ( !is_null( $sectionTitle ) ) {
730 if ( $sectionText == '' ) {
734 $section = "<span class='searchalttitle'>" .
735 $this->msg( 'search-section' )->rawParams(
736 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
741 if ( $categorySnippet ) {
742 $category = "<span class='searchalttitle'>" .
743 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
747 // format text extract
748 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
750 $lang = $this->getLanguage();
752 // format description
753 $byteSize = $result->getByteSize();
754 $wordCount = $result->getWordCount();
755 $timestamp = $result->getTimestamp();
756 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
757 ->numParams( $wordCount )->escaped();
759 if ( $title->getNamespace() == NS_CATEGORY
) {
760 $cat = Category
::newFromTitle( $title );
761 $size = $this->msg( 'search-result-category-size' )
762 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
766 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
769 // Include a thumbnail for media files...
770 if ( $title->getNamespace() == NS_FILE
) {
771 $img = $result->getFile();
772 $img = $img ?
: wfFindFile( $title );
773 if ( $result->isFileMatch() ) {
774 $fileMatch = "<span class='searchalttitle'>" .
775 $this->msg( 'search-file-match' )->escaped() . "</span>";
778 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
780 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
781 // Float doesn't seem to interact well with the bullets.
782 // Table messes up vertical alignment of the bullets.
783 // Bullets are therefore disabled (didn't look great anyway).
785 '<table class="searchResultImage">' .
787 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
788 $thumb->toHtml( array( 'desc-link' => true ) ) .
790 '<td style="vertical-align: top;">' .
791 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
793 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
805 if ( Hooks
::run( 'ShowSearchHit', array(
806 $this, $result, $terms,
807 &$link, &$redirect, &$section, &$extract,
808 &$score, &$size, &$date, &$related,
811 $html = "<li><div class='mw-search-result-heading'>" .
812 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
813 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
821 * Show results from other wikis
823 * @param SearchResultSet|array $matches
824 * @param string $query
828 protected function showInterwiki( $matches, $query ) {
831 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
832 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
833 $out .= "<ul class='mw-search-iwresults'>\n";
835 // work out custom project captions
836 $customCaptions = array();
837 // format per line <iwprefix>:<caption>
838 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
839 foreach ( $customLines as $line ) {
840 $parts = explode( ":", $line, 2 );
841 if ( count( $parts ) == 2 ) { // validate line
842 $customCaptions[$parts[0]] = $parts[1];
846 if ( !is_array( $matches ) ) {
847 $matches = array( $matches );
850 foreach ( $matches as $set ) {
852 $result = $set->next();
854 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
855 $prev = $result->getInterwikiPrefix();
856 $result = $set->next();
860 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
861 $out .= "</ul></div>\n";
863 // convert the whole thing to desired language variant
864 $out = $wgContLang->convert( $out );
870 * Show single interwiki link
872 * @param SearchResult $result
873 * @param string $lastInterwiki
874 * @param string $query
875 * @param array $customCaptions Interwiki prefix -> caption
879 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
881 if ( $result->isBrokenTitle() ) {
885 $title = $result->getTitle();
887 $titleSnippet = $result->getTitleSnippet();
889 if ( $titleSnippet == '' ) {
890 $titleSnippet = null;
893 $link = Linker
::linkKnown(
898 // format redirect if any
899 $redirectTitle = $result->getRedirectTitle();
900 $redirectText = $result->getRedirectSnippet();
902 if ( !is_null( $redirectTitle ) ) {
903 if ( $redirectText == '' ) {
904 $redirectText = null;
907 $redirect = "<span class='searchalttitle'>" .
908 $this->msg( 'search-redirect' )->rawParams(
909 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
914 // display project name
915 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
916 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
917 // captions from 'search-interwiki-custom'
918 $caption = $customCaptions[$title->getInterwiki()];
920 // default is to show the hostname of the other wiki which might suck
921 // if there are many wikis on one hostname
922 $parsed = wfParseUrl( $title->getFullURL() );
923 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
925 // "more results" link (special page stuff could be localized, but we might not know target lang)
926 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
927 $searchLink = Linker
::linkKnown(
929 $this->msg( 'search-interwiki-more' )->text(),
933 'fulltext' => 'Search'
936 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
937 {$searchLink}</span>{$caption}</div>\n<ul>";
940 $out .= "<li>{$link} {$redirect}</li>\n";
946 * Generates the power search box at [[Special:Search]]
948 * @param string $term Search term
950 * @return string HTML form
952 protected function powerSearchBox( $term, $opts ) {
955 // Groups namespaces into rows according to subject
957 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
958 $subject = MWNamespace
::getSubject( $namespace );
959 if ( !array_key_exists( $subject, $rows ) ) {
960 $rows[$subject] = "";
963 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
965 $name = $this->msg( 'blanknamespace' )->text();
969 Xml
::openElement( 'td' ) .
973 "mw-search-ns{$namespace}",
974 in_array( $namespace, $this->namespaces
)
976 Xml
::closeElement( 'td' );
979 $rows = array_values( $rows );
980 $numRows = count( $rows );
982 // Lays out namespaces in multiple floating two-column tables so they'll
983 // be arranged nicely while still accommodating different screen widths
984 $namespaceTables = '';
985 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
986 $namespaceTables .= Xml
::openElement( 'table' );
988 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
989 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
992 $namespaceTables .= Xml
::closeElement( 'table' );
995 $showSections = array( 'namespaceTables' => $namespaceTables );
997 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1000 foreach ( $opts as $key => $value ) {
1001 $hidden .= Html
::hidden( $key, $value );
1004 # Stuff to feed saveNamespaces()
1006 $user = $this->getUser();
1007 if ( $user->isLoggedIn() ) {
1008 $remember .= Xml
::checkLabel(
1009 $this->msg( 'powersearch-remember' )->text(),
1011 'mw-search-powersearch-remember',
1013 // The token goes here rather than in a hidden field so it
1014 // is only sent when necessary (not every form submission).
1015 array( 'value' => $user->getEditToken(
1022 // Return final output
1023 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1024 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1025 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1026 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1027 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1028 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1030 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1032 Xml
::closeElement( 'fieldset' );
1038 protected function getSearchProfiles() {
1039 // Builds list of Search Types (profiles)
1040 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1044 'message' => 'searchprofile-articles',
1045 'tooltip' => 'searchprofile-articles-tooltip',
1046 'namespaces' => SearchEngine
::defaultNamespaces(),
1047 'namespace-messages' => SearchEngine
::namespacesAsText(
1048 SearchEngine
::defaultNamespaces()
1052 'message' => 'searchprofile-images',
1053 'tooltip' => 'searchprofile-images-tooltip',
1054 'namespaces' => array( NS_FILE
),
1057 'message' => 'searchprofile-everything',
1058 'tooltip' => 'searchprofile-everything-tooltip',
1059 'namespaces' => $nsAllSet,
1061 'advanced' => array(
1062 'message' => 'searchprofile-advanced',
1063 'tooltip' => 'searchprofile-advanced-tooltip',
1064 'namespaces' => self
::NAMESPACES_CURRENT
,
1068 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1070 foreach ( $profiles as &$data ) {
1071 if ( !is_array( $data['namespaces'] ) ) {
1074 sort( $data['namespaces'] );
1081 * @param string $term
1084 protected function searchProfileTabs( $term ) {
1085 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1088 if ( $this->startsWithImage( $term ) ) {
1090 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1093 $profiles = $this->getSearchProfiles();
1094 $lang = $this->getLanguage();
1096 // Outputs XML for Search Types
1097 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1098 $out .= Xml
::openElement( 'ul' );
1099 foreach ( $profiles as $id => $profile ) {
1100 if ( !isset( $profile['parameters'] ) ) {
1101 $profile['parameters'] = array();
1103 $profile['parameters']['profile'] = $id;
1105 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1106 $lang->commaList( $profile['namespace-messages'] ) : null;
1110 'class' => $this->profile
=== $id ?
'current' : 'normal'
1112 $this->makeSearchLink(
1115 $this->msg( $profile['message'] )->text(),
1116 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1117 $profile['parameters']
1121 $out .= Xml
::closeElement( 'ul' );
1122 $out .= Xml
::closeElement( 'div' );
1123 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1124 $out .= Xml
::closeElement( 'div' );
1130 * @param string $term Search term
1133 protected function searchOptions( $term ) {
1136 $opts['profile'] = $this->profile
;
1138 if ( $this->isPowerSearch() ) {
1139 $out .= $this->powerSearchBox( $term, $opts );
1142 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1150 * @param string $term
1151 * @param int $resultsShown
1152 * @param int $totalNum
1155 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1156 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1157 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1159 $out .= Html
::input( 'search', $term, 'search', array(
1160 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1162 'autofocus' => trim( $term ) === '',
1163 'class' => 'mw-ui-input mw-ui-input-inline',
1165 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1166 $out .= Html
::submitButton(
1167 $this->msg( 'searchbutton' )->text(),
1168 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1169 array( 'mw-ui-progressive' )
1173 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1174 $top = $this->msg( 'search-showingresults' )
1175 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1176 ->numParams( $resultsShown )
1178 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1179 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1186 * Make a search link with some target namespaces
1188 * @param string $term
1189 * @param array $namespaces Ignored
1190 * @param string $label Link's text
1191 * @param string $tooltip Link's tooltip
1192 * @param array $params Query string parameters
1193 * @return string HTML fragment
1195 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1197 foreach ( $namespaces as $n ) {
1198 $opt['ns' . $n] = 1;
1201 $stParams = array_merge(
1204 'fulltext' => $this->msg( 'search' )->text()
1209 return Xml
::element(
1212 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1220 * Check if query starts with image: prefix
1222 * @param string $term The string to check
1225 protected function startsWithImage( $term ) {
1228 $parts = explode( ':', $term );
1229 if ( count( $parts ) > 1 ) {
1230 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1237 * Check if query starts with all: prefix
1239 * @param string $term The string to check
1242 protected function startsWithAll( $term ) {
1244 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1246 $parts = explode( ':', $term );
1247 if ( count( $parts ) > 1 ) {
1248 return $parts[0] == $allkeyword;
1257 * @return SearchEngine
1259 public function getSearchEngine() {
1260 if ( $this->searchEngine
=== null ) {
1261 $this->searchEngine
= $this->searchEngineType ?
1262 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1265 return $this->searchEngine
;
1269 * Current search profile.
1270 * @return null|string
1272 function getProfile() {
1273 return $this->profile
;
1277 * Current namespaces.
1280 function getNamespaces() {
1281 return $this->namespaces
;
1285 * Users of hook SpecialSearchSetupEngine can use this to
1286 * add more params to links to not lose selection when
1287 * user navigates search results.
1290 * @param string $key
1291 * @param mixed $value
1293 public function setExtraParam( $key, $value ) {
1294 $this->extraParams
[$key] = $value;
1297 protected function getGroupName() {