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' );
369 // show interwiki results if any
370 if ( $textMatches->hasInterwikiResults() ) {
371 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
374 if ( $numTextMatches > 0 ) {
375 $out->addHTML( $this->showMatches( $textMatches ) );
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 );
392 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
395 $out->addHtml( "</div>" );
397 Hooks
::run( 'SpecialSearchResultsAppend', array( $this, $out ) );
402 * Decide if the suggested query should be run, and it's results returned
403 * instead of the provided $textMatches
405 * @param SearchResultSet $textMatches The results of a users query
408 protected function shouldRunSuggestedQuery( SearchResultSet
$textMatches ) {
409 if ( !$this->runSuggestion ||
410 !$textMatches->hasSuggestion() ||
411 $textMatches->numRows() > 0 ||
412 $textMatches->searchContainedSyntax()
417 // Generate a random number between 0 and 1. If the
418 // number is less than the desired percentages run it.
419 $rand = rand( 0, getrandmax() ) / getrandmax();
420 return $this->getConfig()->get( 'SearchRunSuggestedQueryPercent' ) > $rand;
424 * Generates HTML shown to the user when we have a suggestion about a query
425 * that might give more results than their current query.
427 protected function getDidYouMeanHtml( SearchResultSet
$textMatches ) {
428 # mirror Go/Search behavior of original request ..
429 $params = array( 'search' => $textMatches->getSuggestionQuery() );
430 if ( $this->fulltext
!= null ) {
431 $params['fulltext'] = $this->fulltext
;
433 $stParams = array_merge( $params, $this->powerSearchOptions() );
435 $suggest = Linker
::linkKnown(
436 $this->getPageTitle(),
437 $textMatches->getSuggestionSnippet() ?
: null,
442 # html of did you mean... search suggestion link
443 return Html
::rawElement(
445 array( 'class' => 'searchdidyoumean' ),
446 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
451 * Generates HTML shown to user when their query has been internally rewritten,
452 * and the results of the rewritten query are being returned.
454 * @param string $term The users search input
455 * @param SearchResultSet $textMatches The response to the users initial search request
456 * @return string HTML linking the user to their original $term query, and the one
457 * suggested by $textMatches.
459 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet
$textMatches ) {
460 // Showing results for '$rewritten'
461 // Search instead for '$orig'
463 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
464 if ( $this->fulltext
!= null ) {
465 $params['fulltext'] = $this->fulltext
;
467 $stParams = array_merge( $params, $this->powerSearchOptions() );
469 $rewritten = Linker
::linkKnown(
470 $this->getPageTitle(),
471 $textMatches->getQueryAfterRewriteSnippet() ?
: null,
476 $stParams['search'] = $term;
477 $stParams['runsuggestion'] = 0;
478 $original = Linker
::linkKnown(
479 $this->getPageTitle(),
480 htmlspecialchars( $term ),
485 return Html
::rawElement(
487 array( 'class' => 'searchdidyoumean' ),
488 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
493 * @param Title $title
494 * @param int $num The number of search results found
495 * @param null|SearchResultSet $titleMatches Results from title search
496 * @param null|SearchResultSet $textMatches Results from text search
498 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
499 // show direct page/create link if applicable
501 // Check DBkey !== '' in case of fragment link only.
502 if ( is_null( $title ) ||
$title->getDBkey() === ''
503 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
504 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
507 // preserve the paragraph for margins etc...
508 $this->getOutput()->addHtml( '<p></p>' );
513 $messageName = 'searchmenu-new-nocreate';
514 $linkClass = 'mw-search-createlink';
516 if ( !$title->isExternal() ) {
517 if ( $title->isKnown() ) {
518 $messageName = 'searchmenu-exists';
519 $linkClass = 'mw-search-exists';
520 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
521 $messageName = 'searchmenu-new';
527 wfEscapeWikiText( $title->getPrefixedText() ),
528 Message
::numParam( $num )
530 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
532 // Extensions using the hook might still return an empty $messageName
533 if ( $messageName ) {
534 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
536 // preserve the paragraph for margins etc...
537 $this->getOutput()->addHtml( '<p></p>' );
542 * @param string $term
544 protected function setupPage( $term ) {
545 $out = $this->getOutput();
546 if ( strval( $term ) !== '' ) {
547 $out->setPageTitle( $this->msg( 'searchresults' ) );
548 $out->setHTMLTitle( $this->msg( 'pagetitle' )
549 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
550 ->inContentLanguage()->text()
553 // add javascript specific to special:search
554 $out->addModules( 'mediawiki.special.search' );
558 * Return true if current search is a power (advanced) search
562 protected function isPowerSearch() {
563 return $this->profile
=== 'advanced';
567 * Extract "power search" namespace settings from the request object,
568 * returning a list of index numbers to search.
570 * @param WebRequest $request
573 protected function powerSearch( &$request ) {
575 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
576 if ( $request->getCheck( 'ns' . $ns ) ) {
585 * Reconstruct the 'power search' options for links
589 protected function powerSearchOptions() {
591 if ( !$this->isPowerSearch() ) {
592 $opt['profile'] = $this->profile
;
594 foreach ( $this->namespaces
as $n ) {
599 return $opt +
$this->extraParams
;
603 * Save namespace preferences when we're supposed to
605 * @return bool Whether we wrote something
607 protected function saveNamespaces() {
608 $user = $this->getUser();
609 $request = $this->getRequest();
611 if ( $user->isLoggedIn() &&
612 $user->matchEditToken(
613 $request->getVal( 'nsRemember' ),
618 // Reset namespace preferences: namespaces are not searched
619 // when they're not mentioned in the URL parameters.
620 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
621 $user->setOption( 'searchNs' . $n, false );
623 // The request parameters include all the namespaces to be searched.
624 // Even if they're the same as an existing profile, they're not eaten.
625 foreach ( $this->namespaces
as $n ) {
626 $user->setOption( 'searchNs' . $n, true );
629 $user->saveSettings();
637 * Show whole set of results
639 * @param SearchResultSet $matches
643 protected function showMatches( &$matches ) {
646 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
648 $out = "<ul class='mw-search-results'>\n";
649 $result = $matches->next();
651 $out .= $this->showHit( $result, $terms );
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
670 protected function showHit( $result, $terms ) {
672 if ( $result->isBrokenTitle() ) {
676 $title = $result->getTitle();
678 $titleSnippet = $result->getTitleSnippet();
680 if ( $titleSnippet == '' ) {
681 $titleSnippet = null;
684 $link_t = clone $title;
686 Hooks
::run( 'ShowSearchHitTitle',
687 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
689 $link = Linker
::linkKnown(
694 //If page content is not readable, just return the title.
695 //This is not quite safe, but better than showing excerpts from non-readable pages
696 //Note that hiding the entry entirely would screw up paging.
697 if ( !$title->userCan( 'read', $this->getUser() ) ) {
698 return "<li>{$link}</li>\n";
701 // If the page doesn't *exist*... our search index is out of date.
702 // The least confusing at this point is to drop the result.
703 // You may get less results, but... oh well. :P
704 if ( $result->isMissingRevision() ) {
708 // format redirects / relevant sections
709 $redirectTitle = $result->getRedirectTitle();
710 $redirectText = $result->getRedirectSnippet();
711 $sectionTitle = $result->getSectionTitle();
712 $sectionText = $result->getSectionSnippet();
713 $categorySnippet = $result->getCategorySnippet();
716 if ( !is_null( $redirectTitle ) ) {
717 if ( $redirectText == '' ) {
718 $redirectText = null;
721 $redirect = "<span class='searchalttitle'>" .
722 $this->msg( 'search-redirect' )->rawParams(
723 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
728 if ( !is_null( $sectionTitle ) ) {
729 if ( $sectionText == '' ) {
733 $section = "<span class='searchalttitle'>" .
734 $this->msg( 'search-section' )->rawParams(
735 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
740 if ( $categorySnippet ) {
741 $category = "<span class='searchalttitle'>" .
742 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
746 // format text extract
747 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
749 $lang = $this->getLanguage();
751 // format description
752 $byteSize = $result->getByteSize();
753 $wordCount = $result->getWordCount();
754 $timestamp = $result->getTimestamp();
755 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
756 ->numParams( $wordCount )->escaped();
758 if ( $title->getNamespace() == NS_CATEGORY
) {
759 $cat = Category
::newFromTitle( $title );
760 $size = $this->msg( 'search-result-category-size' )
761 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
765 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
768 // Include a thumbnail for media files...
769 if ( $title->getNamespace() == NS_FILE
) {
770 $img = $result->getFile();
771 $img = $img ?
: wfFindFile( $title );
772 if ( $result->isFileMatch() ) {
773 $fileMatch = "<span class='searchalttitle'>" .
774 $this->msg( 'search-file-match' )->escaped() . "</span>";
777 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
779 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
780 // Float doesn't seem to interact well with the bullets.
781 // Table messes up vertical alignment of the bullets.
782 // Bullets are therefore disabled (didn't look great anyway).
784 '<table class="searchResultImage">' .
786 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
787 $thumb->toHtml( array( 'desc-link' => true ) ) .
789 '<td style="vertical-align: top;">' .
790 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
792 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
804 if ( Hooks
::run( 'ShowSearchHit', array(
805 $this, $result, $terms,
806 &$link, &$redirect, &$section, &$extract,
807 &$score, &$size, &$date, &$related,
810 $html = "<li><div class='mw-search-result-heading'>" .
811 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
812 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
820 * Show results from other wikis
822 * @param SearchResultSet|array $matches
823 * @param string $query
827 protected function showInterwiki( $matches, $query ) {
830 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
831 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
832 $out .= "<ul class='mw-search-iwresults'>\n";
834 // work out custom project captions
835 $customCaptions = array();
836 // format per line <iwprefix>:<caption>
837 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
838 foreach ( $customLines as $line ) {
839 $parts = explode( ":", $line, 2 );
840 if ( count( $parts ) == 2 ) { // validate line
841 $customCaptions[$parts[0]] = $parts[1];
845 if ( !is_array( $matches ) ) {
846 $matches = array( $matches );
849 foreach ( $matches as $set ) {
851 $result = $set->next();
853 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
854 $prev = $result->getInterwikiPrefix();
855 $result = $set->next();
859 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
860 $out .= "</ul></div>\n";
862 // convert the whole thing to desired language variant
863 $out = $wgContLang->convert( $out );
869 * Show single interwiki link
871 * @param SearchResult $result
872 * @param string $lastInterwiki
873 * @param string $query
874 * @param array $customCaptions Interwiki prefix -> caption
878 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
880 if ( $result->isBrokenTitle() ) {
884 $title = $result->getTitle();
886 $titleSnippet = $result->getTitleSnippet();
888 if ( $titleSnippet == '' ) {
889 $titleSnippet = null;
892 $link = Linker
::linkKnown(
897 // format redirect if any
898 $redirectTitle = $result->getRedirectTitle();
899 $redirectText = $result->getRedirectSnippet();
901 if ( !is_null( $redirectTitle ) ) {
902 if ( $redirectText == '' ) {
903 $redirectText = null;
906 $redirect = "<span class='searchalttitle'>" .
907 $this->msg( 'search-redirect' )->rawParams(
908 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
913 // display project name
914 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
915 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
916 // captions from 'search-interwiki-custom'
917 $caption = $customCaptions[$title->getInterwiki()];
919 // default is to show the hostname of the other wiki which might suck
920 // if there are many wikis on one hostname
921 $parsed = wfParseUrl( $title->getFullURL() );
922 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
924 // "more results" link (special page stuff could be localized, but we might not know target lang)
925 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
926 $searchLink = Linker
::linkKnown(
928 $this->msg( 'search-interwiki-more' )->text(),
932 'fulltext' => 'Search'
935 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
936 {$searchLink}</span>{$caption}</div>\n<ul>";
939 $out .= "<li>{$link} {$redirect}</li>\n";
945 * Generates the power search box at [[Special:Search]]
947 * @param string $term Search term
949 * @return string HTML form
951 protected function powerSearchBox( $term, $opts ) {
954 // Groups namespaces into rows according to subject
956 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
957 $subject = MWNamespace
::getSubject( $namespace );
958 if ( !array_key_exists( $subject, $rows ) ) {
959 $rows[$subject] = "";
962 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
964 $name = $this->msg( 'blanknamespace' )->text();
968 Xml
::openElement( 'td' ) .
972 "mw-search-ns{$namespace}",
973 in_array( $namespace, $this->namespaces
)
975 Xml
::closeElement( 'td' );
978 $rows = array_values( $rows );
979 $numRows = count( $rows );
981 // Lays out namespaces in multiple floating two-column tables so they'll
982 // be arranged nicely while still accommodating different screen widths
983 $namespaceTables = '';
984 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
985 $namespaceTables .= Xml
::openElement( 'table' );
987 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
988 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
991 $namespaceTables .= Xml
::closeElement( 'table' );
994 $showSections = array( 'namespaceTables' => $namespaceTables );
996 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
999 foreach ( $opts as $key => $value ) {
1000 $hidden .= Html
::hidden( $key, $value );
1003 # Stuff to feed saveNamespaces()
1005 $user = $this->getUser();
1006 if ( $user->isLoggedIn() ) {
1007 $remember .= Xml
::checkLabel(
1008 $this->msg( 'powersearch-remember' )->text(),
1010 'mw-search-powersearch-remember',
1012 // The token goes here rather than in a hidden field so it
1013 // is only sent when necessary (not every form submission).
1014 array( 'value' => $user->getEditToken(
1021 // Return final output
1022 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1023 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1024 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1025 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1026 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1027 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1029 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1031 Xml
::closeElement( 'fieldset' );
1037 protected function getSearchProfiles() {
1038 // Builds list of Search Types (profiles)
1039 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1043 'message' => 'searchprofile-articles',
1044 'tooltip' => 'searchprofile-articles-tooltip',
1045 'namespaces' => SearchEngine
::defaultNamespaces(),
1046 'namespace-messages' => SearchEngine
::namespacesAsText(
1047 SearchEngine
::defaultNamespaces()
1051 'message' => 'searchprofile-images',
1052 'tooltip' => 'searchprofile-images-tooltip',
1053 'namespaces' => array( NS_FILE
),
1056 'message' => 'searchprofile-everything',
1057 'tooltip' => 'searchprofile-everything-tooltip',
1058 'namespaces' => $nsAllSet,
1060 'advanced' => array(
1061 'message' => 'searchprofile-advanced',
1062 'tooltip' => 'searchprofile-advanced-tooltip',
1063 'namespaces' => self
::NAMESPACES_CURRENT
,
1067 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
1069 foreach ( $profiles as &$data ) {
1070 if ( !is_array( $data['namespaces'] ) ) {
1073 sort( $data['namespaces'] );
1080 * @param string $term
1083 protected function searchProfileTabs( $term ) {
1084 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1087 if ( $this->startsWithImage( $term ) ) {
1089 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1092 $profiles = $this->getSearchProfiles();
1093 $lang = $this->getLanguage();
1095 // Outputs XML for Search Types
1096 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1097 $out .= Xml
::openElement( 'ul' );
1098 foreach ( $profiles as $id => $profile ) {
1099 if ( !isset( $profile['parameters'] ) ) {
1100 $profile['parameters'] = array();
1102 $profile['parameters']['profile'] = $id;
1104 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1105 $lang->commaList( $profile['namespace-messages'] ) : null;
1109 'class' => $this->profile
=== $id ?
'current' : 'normal'
1111 $this->makeSearchLink(
1114 $this->msg( $profile['message'] )->text(),
1115 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1116 $profile['parameters']
1120 $out .= Xml
::closeElement( 'ul' );
1121 $out .= Xml
::closeElement( 'div' );
1122 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1123 $out .= Xml
::closeElement( 'div' );
1129 * @param string $term Search term
1132 protected function searchOptions( $term ) {
1135 $opts['profile'] = $this->profile
;
1137 if ( $this->isPowerSearch() ) {
1138 $out .= $this->powerSearchBox( $term, $opts );
1141 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1149 * @param string $term
1150 * @param int $resultsShown
1151 * @param int $totalNum
1154 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1155 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1156 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1158 $out .= Html
::input( 'search', $term, 'search', array(
1159 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1161 'autofocus' => trim( $term ) === '',
1162 'class' => 'mw-ui-input mw-ui-input-inline',
1164 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1165 $out .= Html
::submitButton(
1166 $this->msg( 'searchbutton' )->text(),
1167 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1168 array( 'mw-ui-progressive' )
1172 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1173 $top = $this->msg( 'search-showingresults' )
1174 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1175 ->numParams( $resultsShown )
1177 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1178 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1185 * Make a search link with some target namespaces
1187 * @param string $term
1188 * @param array $namespaces Ignored
1189 * @param string $label Link's text
1190 * @param string $tooltip Link's tooltip
1191 * @param array $params Query string parameters
1192 * @return string HTML fragment
1194 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1196 foreach ( $namespaces as $n ) {
1197 $opt['ns' . $n] = 1;
1200 $stParams = array_merge(
1203 'fulltext' => $this->msg( 'search' )->text()
1208 return Xml
::element(
1211 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1219 * Check if query starts with image: prefix
1221 * @param string $term The string to check
1224 protected function startsWithImage( $term ) {
1227 $parts = explode( ':', $term );
1228 if ( count( $parts ) > 1 ) {
1229 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1236 * Check if query starts with all: prefix
1238 * @param string $term The string to check
1241 protected function startsWithAll( $term ) {
1243 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1245 $parts = explode( ':', $term );
1246 if ( count( $parts ) > 1 ) {
1247 return $parts[0] == $allkeyword;
1256 * @return SearchEngine
1258 public function getSearchEngine() {
1259 if ( $this->searchEngine
=== null ) {
1260 $this->searchEngine
= $this->searchEngineType ?
1261 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1264 return $this->searchEngine
;
1268 * Current search profile.
1269 * @return null|string
1271 function getProfile() {
1272 return $this->profile
;
1276 * Current namespaces.
1279 function getNamespaces() {
1280 return $this->namespaces
;
1284 * Users of hook SpecialSearchSetupEngine can use this to
1285 * add more params to links to not lose selection when
1286 * user navigates search results.
1289 * @param string $key
1290 * @param mixed $value
1292 public function setExtraParam( $key, $value ) {
1293 $this->extraParams
[$key] = $value;
1296 protected function getGroupName() {