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, help, 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.
42 protected $searchEngine;
44 /// Search engine type, if not default
45 protected $searchEngineType;
48 protected $extraParams = array();
50 /// No idea, apparently used by some other classes
56 protected $limit, $offset;
61 protected $namespaces;
66 protected $didYouMeanHtml, $fulltext;
68 const NAMESPACES_CURRENT
= 'sense';
70 public function __construct() {
71 parent
::__construct( 'Search' );
77 * @param string $par or null
79 public function execute( $par ) {
81 $this->outputHeader();
82 $out = $this->getOutput();
83 $out->allowClickjacking();
84 $out->addModuleStyles( array(
85 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
92 $request = $this->getRequest();
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 $this->searchEngineType
= $request->getVal( 'srbackend' );
101 if ( $request->getVal( 'fulltext' )
102 ||
!is_null( $request->getVal( 'offset' ) )
104 $this->showResults( $search );
106 $this->goResult( $search );
111 * Set up basic search parameters from the request and user settings.
113 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
115 public function load() {
116 $request = $this->getRequest();
117 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20 );
118 $this->mPrefix
= $request->getVal( 'prefix', '' );
120 $user = $this->getUser();
122 # Extract manually requested namespaces
123 $nslist = $this->powerSearch( $request );
124 if ( !count( $nslist ) ) {
125 # Fallback to user preference
126 $nslist = SearchEngine
::userNamespaces( $user );
130 if ( !count( $nslist ) ) {
131 $profile = 'default';
134 $profile = $request->getVal( 'profile', $profile );
135 $profiles = $this->getSearchProfiles();
136 if ( $profile === null ) {
137 // BC with old request format
138 $profile = 'advanced';
139 foreach ( $profiles as $key => $data ) {
140 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
144 $this->namespaces
= $nslist;
145 } elseif ( $profile === 'advanced' ) {
146 $this->namespaces
= $nslist;
148 if ( isset( $profiles[$profile]['namespaces'] ) ) {
149 $this->namespaces
= $profiles[$profile]['namespaces'];
151 // Unknown profile requested
152 $profile = 'default';
153 $this->namespaces
= $profiles['default']['namespaces'];
157 $this->didYouMeanHtml
= ''; # html of did you mean... link
158 $this->fulltext
= $request->getVal( 'fulltext' );
159 $this->profile
= $profile;
163 * If an exact title match can be found, jump straight ahead to it.
165 * @param $term String
167 public function goResult( $term ) {
168 $this->setupPage( $term );
169 # Try to go to page as entered.
170 $t = Title
::newFromText( $term );
171 # If the string cannot be used to create a title
172 if ( is_null( $t ) ) {
173 $this->showResults( $term );
177 # If there's an exact or very near match, jump right there.
178 $t = SearchEngine
::getNearMatch( $term );
180 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
181 # Hook requested termination
185 if ( !is_null( $t ) ) {
186 $this->getOutput()->redirect( $t->getFullURL() );
190 # No match, generate an edit URL
191 $t = Title
::newFromText( $term );
192 if ( !is_null( $t ) ) {
194 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
195 wfDebugLog( 'nogomatch', $t->getFullText(), 'private' );
197 # If the feature is enabled, go straight to the edit page
199 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
204 $this->showResults( $term );
208 * @param $term String
210 public function showResults( $term ) {
211 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
213 $profile = new ProfileSection( __METHOD__
);
214 $search = $this->getSearchEngine();
215 $search->setLimitOffset( $this->limit
, $this->offset
);
216 $search->setNamespaces( $this->namespaces
);
217 $search->prefix
= $this->mPrefix
;
218 $term = $search->transformSearchTerm( $term );
220 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
222 $this->setupPage( $term );
224 $out = $this->getOutput();
226 if ( $wgDisableTextSearch ) {
227 if ( $wgSearchForwardUrl ) {
228 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
229 $out->redirect( $url );
232 Xml
::openElement( 'fieldset' ) .
233 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
234 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
235 $this->msg( 'googlesearch' )->rawParams(
236 htmlspecialchars( $term ),
238 $this->msg( 'searchbutton' )->escaped()
240 Xml
::closeElement( 'fieldset' )
247 $t = Title
::newFromText( $term );
248 $showSuggestion = $t === null ||
!$t->isKnown();
249 $search->setShowSuggestion( $showSuggestion );
251 // fetch search results
252 $rewritten = $search->replacePrefixes( $term );
254 $titleMatches = $search->searchTitle( $rewritten );
255 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
256 $textMatches = $search->searchText( $rewritten );
260 if ( $textMatches instanceof Status
) {
261 $textStatus = $textMatches;
265 // did you mean... suggestions
266 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
267 $st = SpecialPage
::getTitleFor( 'Search' );
269 # mirror Go/Search behavior of original request ..
270 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
272 if ( $this->fulltext
!= null ) {
273 $didYouMeanParams['fulltext'] = $this->fulltext
;
276 $stParams = array_merge(
278 $this->powerSearchOptions()
281 $suggestionSnippet = $textMatches->getSuggestionSnippet();
283 if ( $suggestionSnippet == '' ) {
284 $suggestionSnippet = null;
287 $suggestLink = Linker
::linkKnown(
294 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
297 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
298 # Hook requested termination
302 // start rendering the page
307 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
309 'action' => $wgScript
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 ) .
319 Xml
::closeElement( 'div' )
322 // Sometimes the search engine knows there are too many hits
323 if ( $titleMatches instanceof SearchResultTooMany
) {
324 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
329 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
330 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
331 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
332 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
333 $out->addHTML( '</form>' );
335 // Empty query -- straight view of search form
339 // Get number of results
340 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
341 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
342 // Total initial query matches (possible false positives)
343 $num = $titleMatchesNum +
$textMatchesNum;
345 // Get total actual results (after second filtering, if any)
346 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
347 $titleMatches->getTotalHits() : $titleMatchesNum;
348 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
349 $textMatches->getTotalHits() : $textMatchesNum;
351 // get total number of results if backend can calculate it
353 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
354 $totalRes +
= $titleMatches->getTotalHits();
356 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
357 $totalRes +
= $textMatches->getTotalHits();
360 // show number of results and current offset
361 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
362 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
364 $out->addHtml( Xml
::closeElement( 'form' ) );
365 $out->addHtml( "<div class='searchresults'>" );
368 if ( $num ||
$this->offset
) {
369 // Show the create link ahead
370 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
371 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
372 $this->powerSearchOptions() +
array( 'search' => $term ),
373 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
375 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
376 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
378 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
381 $out->parserOptions()->setEditSection( false );
382 if ( $titleMatches ) {
383 if ( $numTitleMatches > 0 ) {
384 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
385 $out->addHTML( $this->showMatches( $titleMatches ) );
387 $titleMatches->free();
389 if ( $textMatches && !$textStatus ) {
390 // output appropriate heading
391 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
392 // if no title matches the heading is redundant
393 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
394 } elseif ( $totalRes == 0 ) {
395 # Don't show the 'no text matches' if we received title matches
396 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
398 // show interwiki results if any
399 if ( $textMatches->hasInterwikiResults() ) {
400 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
403 if ( $numTextMatches > 0 ) {
404 $out->addHTML( $this->showMatches( $textMatches ) );
407 $textMatches->free();
411 $out->addHTML( '<div class="error">' .
412 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
414 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
415 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
416 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
419 $out->addHtml( "</div>" );
421 if ( $num ||
$this->offset
) {
422 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
424 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
429 * @param int $num The number of search results found
430 * @param $titleMatches null|SearchResultSet results from title search
431 * @param $textMatches null|SearchResultSet results from text search
433 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
434 // show direct page/create link if applicable
436 // Check DBkey !== '' in case of fragment link only.
437 if ( is_null( $t ) ||
$t->getDBkey() === ''
438 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
439 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
442 // preserve the paragraph for margins etc...
443 $this->getOutput()->addHtml( '<p></p>' );
448 if ( $t->isKnown() ) {
449 $messageName = 'searchmenu-exists';
450 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
451 $messageName = 'searchmenu-new';
453 $messageName = 'searchmenu-new-nocreate';
455 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
456 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
458 // Extensions using the hook might still return an empty $messageName
459 if ( $messageName ) {
460 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
462 // preserve the paragraph for margins etc...
463 $this->getOutput()->addHtml( '<p></p>' );
468 * @param $term string
470 protected function setupPage( $term ) {
471 # Should advanced UI be used?
472 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
473 $out = $this->getOutput();
474 if ( strval( $term ) !== '' ) {
475 $out->setPageTitle( $this->msg( 'searchresults' ) );
476 $out->setHTMLTitle( $this->msg( 'pagetitle' )
477 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
478 ->inContentLanguage()->text()
481 // add javascript specific to special:search
482 $out->addModules( 'mediawiki.special.search' );
486 * Extract "power search" namespace settings from the request object,
487 * returning a list of index numbers to search.
489 * @param $request WebRequest
492 protected function powerSearch( &$request ) {
494 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
495 if ( $request->getCheck( 'ns' . $ns ) ) {
504 * Reconstruct the 'power search' options for links
508 protected function powerSearchOptions() {
510 if ( $this->profile
!== 'advanced' ) {
511 $opt['profile'] = $this->profile
;
513 foreach ( $this->namespaces
as $n ) {
518 return $opt +
$this->extraParams
;
522 * Show whole set of results
524 * @param $matches SearchResultSet
528 protected function showMatches( &$matches ) {
531 $profile = new ProfileSection( __METHOD__
);
532 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
534 $out = "<ul class='mw-search-results'>\n";
535 $result = $matches->next();
537 $out .= $this->showHit( $result, $terms );
538 $result = $matches->next();
542 // convert the whole thing to desired language variant
543 $out = $wgContLang->convert( $out );
549 * Format a single hit result
551 * @param $result SearchResult
552 * @param array $terms terms to highlight
556 protected function showHit( $result, $terms ) {
557 $profile = new ProfileSection( __METHOD__
);
559 if ( $result->isBrokenTitle() ) {
560 return "<!-- Broken link in search result -->\n";
563 $t = $result->getTitle();
565 $titleSnippet = $result->getTitleSnippet( $terms );
567 if ( $titleSnippet == '' ) {
568 $titleSnippet = null;
573 wfRunHooks( 'ShowSearchHitTitle',
574 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
576 $link = Linker
::linkKnown(
581 //If page content is not readable, just return the title.
582 //This is not quite safe, but better than showing excerpts from non-readable pages
583 //Note that hiding the entry entirely would screw up paging.
584 if ( !$t->userCan( 'read', $this->getUser() ) ) {
585 return "<li>{$link}</li>\n";
588 // If the page doesn't *exist*... our search index is out of date.
589 // The least confusing at this point is to drop the result.
590 // You may get less results, but... oh well. :P
591 if ( $result->isMissingRevision() ) {
592 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
595 // format redirects / relevant sections
596 $redirectTitle = $result->getRedirectTitle();
597 $redirectText = $result->getRedirectSnippet( $terms );
598 $sectionTitle = $result->getSectionTitle();
599 $sectionText = $result->getSectionSnippet( $terms );
602 if ( !is_null( $redirectTitle ) ) {
603 if ( $redirectText == '' ) {
604 $redirectText = null;
607 $redirect = "<span class='searchalttitle'>" .
608 $this->msg( 'search-redirect' )->rawParams(
609 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
615 if ( !is_null( $sectionTitle ) ) {
616 if ( $sectionText == '' ) {
620 $section = "<span class='searchalttitle'>" .
621 $this->msg( 'search-section' )->rawParams(
622 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
626 // format text extract
627 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
629 $lang = $this->getLanguage();
632 if ( is_null( $result->getScore() ) ) {
633 // Search engine doesn't report scoring info
636 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
637 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
641 // format description
642 $byteSize = $result->getByteSize();
643 $wordCount = $result->getWordCount();
644 $timestamp = $result->getTimestamp();
645 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
646 ->numParams( $wordCount )->escaped();
648 if ( $t->getNamespace() == NS_CATEGORY
) {
649 $cat = Category
::newFromTitle( $t );
650 $size = $this->msg( 'search-result-category-size' )
651 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
655 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
657 // link to related articles if supported
659 if ( $result->hasRelated() ) {
660 $st = SpecialPage
::getTitleFor( 'Search' );
661 $stParams = array_merge(
662 $this->powerSearchOptions(),
664 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
665 ':' . $t->getPrefixedText(),
666 'fulltext' => $this->msg( 'search' )->text()
670 $related = ' -- ' . Linker
::linkKnown(
672 $this->msg( 'search-relatedarticle' )->text(),
679 // Include a thumbnail for media files...
680 if ( $t->getNamespace() == NS_FILE
) {
681 $img = $result->getFile();
682 $img = $img ?
: wfFindFile( $t );
683 if ( $result->isFileMatch() ) {
684 $fileMatch = "<span class='searchalttitle'>" .
685 $this->msg( 'search-file-match' )->escaped() . "</span>";
688 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
690 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
691 // Float doesn't seem to interact well with the bullets.
692 // Table messes up vertical alignment of the bullets.
693 // Bullets are therefore disabled (didn't look great anyway).
695 '<table class="searchResultImage">' .
697 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
698 $thumb->toHtml( array( 'desc-link' => true ) ) .
700 '<td style="vertical-align: top;">' .
701 "{$link} {$fileMatch}" .
703 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
714 if ( wfRunHooks( 'ShowSearchHit', array(
715 $this, $result, $terms,
716 &$link, &$redirect, &$section, &$extract,
717 &$score, &$size, &$date, &$related,
720 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
721 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
729 * Show results from other wikis
731 * @param $matches SearchResultSet|array
732 * @param $query String
736 protected function showInterwiki( $matches, $query ) {
738 $profile = new ProfileSection( __METHOD__
);
740 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
741 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
742 $out .= "<ul class='mw-search-iwresults'>\n";
744 // work out custom project captions
745 $customCaptions = array();
746 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
747 foreach ( $customLines as $line ) {
748 $parts = explode( ":", $line, 2 );
749 if ( count( $parts ) == 2 ) { // validate line
750 $customCaptions[$parts[0]] = $parts[1];
754 if ( !is_array( $matches ) ) {
755 $matches = array( $matches );
758 foreach ( $matches as $set ) {
760 $result = $set->next();
762 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
763 $prev = $result->getInterwikiPrefix();
764 $result = $set->next();
769 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
770 $out .= "</ul></div>\n";
772 // convert the whole thing to desired language variant
773 $out = $wgContLang->convert( $out );
779 * Show single interwiki link
781 * @param $result SearchResult
782 * @param $lastInterwiki String
783 * @param $query String
784 * @param array $customCaptions iw prefix -> caption
788 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
789 $profile = new ProfileSection( __METHOD__
);
791 if ( $result->isBrokenTitle() ) {
792 return "<!-- Broken link in search result -->\n";
795 $t = $result->getTitle();
797 $titleSnippet = $result->getTitleSnippet();
799 if ( $titleSnippet == '' ) {
800 $titleSnippet = null;
803 $link = Linker
::linkKnown(
808 // format redirect if any
809 $redirectTitle = $result->getRedirectTitle();
810 $redirectText = $result->getRedirectSnippet();
812 if ( !is_null( $redirectTitle ) ) {
813 if ( $redirectText == '' ) {
814 $redirectText = null;
817 $redirect = "<span class='searchalttitle'>" .
818 $this->msg( 'search-redirect' )->rawParams(
819 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
824 // display project name
825 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
826 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
827 // captions from 'search-interwiki-custom'
828 $caption = $customCaptions[$t->getInterwiki()];
830 // default is to show the hostname of the other wiki which might suck
831 // if there are many wikis on one hostname
832 $parsed = wfParseUrl( $t->getFullURL() );
833 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
835 // "more results" link (special page stuff could be localized, but we might not know target lang)
836 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
837 $searchLink = Linker
::linkKnown(
839 $this->msg( 'search-interwiki-more' )->text(),
843 'fulltext' => 'Search'
846 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
847 {$searchLink}</span>{$caption}</div>\n<ul>";
850 $out .= "<li>{$link} {$redirect}</li>\n";
860 protected function getProfileForm( $profile, $term ) {
863 $opts['profile'] = $this->profile
;
865 if ( $profile === 'advanced' ) {
866 return $this->powerSearchBox( $term, $opts );
869 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
876 * Generates the power search box at [[Special:Search]]
878 * @param string $term search term
880 * @return String: HTML form
882 protected function powerSearchBox( $term, $opts ) {
885 // Groups namespaces into rows according to subject
887 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
888 $subject = MWNamespace
::getSubject( $namespace );
889 if ( !array_key_exists( $subject, $rows ) ) {
890 $rows[$subject] = "";
893 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
895 $name = $this->msg( 'blanknamespace' )->text();
900 'td', array( 'style' => 'white-space: nowrap' )
905 "mw-search-ns{$namespace}",
906 in_array( $namespace, $this->namespaces
)
908 Xml
::closeElement( 'td' );
911 $rows = array_values( $rows );
912 $numRows = count( $rows );
914 // Lays out namespaces in multiple floating two-column tables so they'll
915 // be arranged nicely while still accommodating different screen widths
916 $namespaceTables = '';
917 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
918 $namespaceTables .= Xml
::openElement(
920 array( 'cellpadding' => 0, 'cellspacing' => 0 )
923 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
924 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
927 $namespaceTables .= Xml
::closeElement( 'table' );
930 $showSections = array( 'namespaceTables' => $namespaceTables );
932 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
935 foreach ( $opts as $key => $value ) {
936 $hidden .= Html
::hidden( $key, $value );
939 // Return final output
940 return Xml
::openElement(
942 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
944 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
945 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
946 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
947 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
948 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
950 Xml
::closeElement( 'fieldset' );
956 protected function getSearchProfiles() {
957 // Builds list of Search Types (profiles)
958 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
962 'message' => 'searchprofile-articles',
963 'tooltip' => 'searchprofile-articles-tooltip',
964 'namespaces' => SearchEngine
::defaultNamespaces(),
965 'namespace-messages' => SearchEngine
::namespacesAsText(
966 SearchEngine
::defaultNamespaces()
970 'message' => 'searchprofile-images',
971 'tooltip' => 'searchprofile-images-tooltip',
972 'namespaces' => array( NS_FILE
),
975 'message' => 'searchprofile-project',
976 'tooltip' => 'searchprofile-project-tooltip',
977 'namespaces' => SearchEngine
::helpNamespaces(),
978 'namespace-messages' => SearchEngine
::namespacesAsText(
979 SearchEngine
::helpNamespaces()
983 'message' => 'searchprofile-everything',
984 'tooltip' => 'searchprofile-everything-tooltip',
985 'namespaces' => $nsAllSet,
988 'message' => 'searchprofile-advanced',
989 'tooltip' => 'searchprofile-advanced-tooltip',
990 'namespaces' => self
::NAMESPACES_CURRENT
,
994 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
996 foreach ( $profiles as &$data ) {
997 if ( !is_array( $data['namespaces'] ) ) {
1000 sort( $data['namespaces'] );
1008 * @param $resultsShown
1012 protected function formHeader( $term, $resultsShown, $totalNum ) {
1013 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1016 if ( $this->startsWithImage( $term ) ) {
1018 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1021 $profiles = $this->getSearchProfiles();
1022 $lang = $this->getLanguage();
1024 // Outputs XML for Search Types
1025 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1026 $out .= Xml
::openElement( 'ul' );
1027 foreach ( $profiles as $id => $profile ) {
1028 if ( !isset( $profile['parameters'] ) ) {
1029 $profile['parameters'] = array();
1031 $profile['parameters']['profile'] = $id;
1033 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1034 $lang->commaList( $profile['namespace-messages'] ) : null;
1038 'class' => $this->profile
=== $id ?
'current' : 'normal'
1040 $this->makeSearchLink(
1043 $this->msg( $profile['message'] )->text(),
1044 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1045 $profile['parameters']
1049 $out .= Xml
::closeElement( 'ul' );
1050 $out .= Xml
::closeElement( 'div' );
1053 if ( $resultsShown > 0 ) {
1054 if ( $totalNum > 0 ) {
1055 $top = $this->msg( 'showingresultsheader' )
1056 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1057 ->params( wfEscapeWikiText( $term ) )
1058 ->numParams( $resultsShown )
1060 } elseif ( $resultsShown >= $this->limit
) {
1061 $top = $this->msg( 'showingresults' )
1062 ->numParams( $this->limit
, $this->offset +
1 )
1065 $top = $this->msg( 'showingresultsnum' )
1066 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1069 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1070 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1074 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1075 $out .= Xml
::closeElement( 'div' );
1081 * @param $term string
1084 protected function shortDialog( $term ) {
1085 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1086 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1088 $out .= Html
::input( 'search', $term, 'search', array(
1089 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1092 'class' => 'mw-ui-input',
1094 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1095 $out .= Xml
::submitButton(
1096 $this->msg( 'searchbutton' )->text(),
1097 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1100 return $out . $this->didYouMeanHtml
;
1104 * Make a search link with some target namespaces
1106 * @param $term String
1107 * @param array $namespaces ignored
1108 * @param string $label link's text
1109 * @param string $tooltip link's tooltip
1110 * @param array $params query string parameters
1111 * @return String: HTML fragment
1113 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1115 foreach ( $namespaces as $n ) {
1116 $opt['ns' . $n] = 1;
1119 $stParams = array_merge(
1122 'fulltext' => $this->msg( 'search' )->text()
1127 return Xml
::element(
1130 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1138 * Check if query starts with image: prefix
1140 * @param string $term the string to check
1143 protected function startsWithImage( $term ) {
1146 $p = explode( ':', $term );
1147 if ( count( $p ) > 1 ) {
1148 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1155 * Check if query starts with all: prefix
1157 * @param string $term the string to check
1160 protected function startsWithAll( $term ) {
1162 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1164 $p = explode( ':', $term );
1165 if ( count( $p ) > 1 ) {
1166 return $p[0] == $allkeyword;
1175 * @return SearchEngine
1177 public function getSearchEngine() {
1178 if ( $this->searchEngine
=== null ) {
1179 $this->searchEngine
= $this->searchEngineType ?
1180 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1183 return $this->searchEngine
;
1187 * Current search profile.
1188 * @return null|string
1190 function getProfile() {
1191 return $this->profile
;
1195 * Current namespaces.
1198 function getNamespaces() {
1199 return $this->namespaces
;
1203 * Users of hook SpecialSearchSetupEngine can use this to
1204 * add more params to links to not lose selection when
1205 * user navigates search results.
1211 public function setExtraParam( $key, $value ) {
1212 $this->extraParams
[$key] = $value;
1215 protected function getGroupName() {