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 $searchRedirects;
71 protected $didYouMeanHtml, $fulltext;
73 const NAMESPACES_CURRENT
= 'sense';
75 public function __construct() {
76 parent
::__construct( 'Search' );
82 * @param string $par or null
84 public function execute( $par ) {
86 $this->outputHeader();
87 $out = $this->getOutput();
88 $out->allowClickjacking();
89 $out->addModuleStyles( array(
90 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
93 // Strip underscores from title parameter; most of the time we'll want
94 // text form here. But don't strip underscores from actual text params!
95 $titleParam = str_replace( '_', ' ', $par );
97 $request = $this->getRequest();
99 // Fetch the search term
100 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
104 $this->searchEngineType
= $request->getVal( 'srbackend' );
106 if ( $request->getVal( 'fulltext' )
107 ||
!is_null( $request->getVal( 'offset' ) )
109 $this->showResults( $search );
111 $this->goResult( $search );
116 * Set up basic search parameters from the request and user settings.
118 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
120 public function load() {
121 $request = $this->getRequest();
122 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20 );
123 $this->mPrefix
= $request->getVal( 'prefix', '' );
125 $user = $this->getUser();
127 # Extract manually requested namespaces
128 $nslist = $this->powerSearch( $request );
129 if ( !count( $nslist ) ) {
130 # Fallback to user preference
131 $nslist = SearchEngine
::userNamespaces( $user );
135 if ( !count( $nslist ) ) {
136 $profile = 'default';
139 $profile = $request->getVal( 'profile', $profile );
140 $profiles = $this->getSearchProfiles();
141 if ( $profile === null ) {
142 // BC with old request format
143 $profile = 'advanced';
144 foreach ( $profiles as $key => $data ) {
145 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
149 $this->namespaces
= $nslist;
150 } elseif ( $profile === 'advanced' ) {
151 $this->namespaces
= $nslist;
153 if ( isset( $profiles[$profile]['namespaces'] ) ) {
154 $this->namespaces
= $profiles[$profile]['namespaces'];
156 // Unknown profile requested
157 $profile = 'default';
158 $this->namespaces
= $profiles['default']['namespaces'];
162 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
163 $default = $request->getBool( 'profile' ) ?
0 : 1;
164 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
165 $this->didYouMeanHtml
= ''; # html of did you mean... link
166 $this->fulltext
= $request->getVal( 'fulltext' );
167 $this->profile
= $profile;
171 * If an exact title match can be found, jump straight ahead to it.
173 * @param $term String
175 public function goResult( $term ) {
176 $this->setupPage( $term );
177 # Try to go to page as entered.
178 $t = Title
::newFromText( $term );
179 # If the string cannot be used to create a title
180 if ( is_null( $t ) ) {
181 $this->showResults( $term );
184 # If there's an exact or very near match, jump right there.
185 $t = SearchEngine
::getNearMatch( $term );
187 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
188 # Hook requested termination
192 if ( !is_null( $t ) ) {
193 $this->getOutput()->redirect( $t->getFullURL() );
196 # No match, generate an edit URL
197 $t = Title
::newFromText( $term );
198 if ( !is_null( $t ) ) {
200 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
201 wfDebugLog( 'nogomatch', $t->getFullText(), 'private' );
203 # If the feature is enabled, go straight to the edit page
205 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
209 $this->showResults( $term );
213 * @param $term String
215 public function showResults( $term ) {
216 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
218 $profile = new ProfileSection( __METHOD__
);
219 $search = $this->getSearchEngine();
220 $search->setLimitOffset( $this->limit
, $this->offset
);
221 $search->setNamespaces( $this->namespaces
);
222 $search->showRedirects
= $this->searchRedirects
; // BC
223 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
224 $search->prefix
= $this->mPrefix
;
225 $term = $search->transformSearchTerm( $term );
227 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
229 $this->setupPage( $term );
231 $out = $this->getOutput();
233 if ( $wgDisableTextSearch ) {
234 if ( $wgSearchForwardUrl ) {
235 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
236 $out->redirect( $url );
239 Xml
::openElement( 'fieldset' ) .
240 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
241 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
242 $this->msg( 'googlesearch' )->rawParams(
243 htmlspecialchars( $term ),
245 $this->msg( 'searchbutton' )->escaped()
247 Xml
::closeElement( 'fieldset' )
253 $t = Title
::newFromText( $term );
254 $showSuggestion = $t === null ||
!$t->isKnown();
255 $search->setShowSuggestion( $showSuggestion );
257 // fetch search results
258 $rewritten = $search->replacePrefixes( $term );
260 $titleMatches = $search->searchTitle( $rewritten );
261 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
262 $textMatches = $search->searchText( $rewritten );
266 if ( $textMatches instanceof Status
) {
267 $textStatus = $textMatches;
271 // did you mean... suggestions
272 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
273 $st = SpecialPage
::getTitleFor( 'Search' );
275 # mirror Go/Search behavior of original request ..
276 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
278 if ( $this->fulltext
!= null ) {
279 $didYouMeanParams['fulltext'] = $this->fulltext
;
282 $stParams = array_merge(
284 $this->powerSearchOptions()
287 $suggestionSnippet = $textMatches->getSuggestionSnippet();
289 if ( $suggestionSnippet == '' ) {
290 $suggestionSnippet = null;
293 $suggestLink = Linker
::linkKnown(
300 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
303 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
304 # Hook requested termination
308 // start rendering the page
313 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
315 'action' => $wgScript
320 # This is an awful awful ID name. It's not a table, but we
321 # named it poorly from when this was a table so now we're
323 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
324 $this->shortDialog( $term ) .
325 Xml
::closeElement( 'div' )
328 // Sometimes the search engine knows there are too many hits
329 if ( $titleMatches instanceof SearchResultTooMany
) {
330 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
334 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
335 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
336 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
337 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
338 $out->addHTML( '</form>' );
339 // Empty query -- straight view of search form
343 // Get number of results
344 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
345 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
346 // Total initial query matches (possible false positives)
347 $num = $titleMatchesNum +
$textMatchesNum;
349 // Get total actual results (after second filtering, if any)
350 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
351 $titleMatches->getTotalHits() : $titleMatchesNum;
352 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
353 $textMatches->getTotalHits() : $textMatchesNum;
355 // get total number of results if backend can calculate it
357 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
358 $totalRes +
= $titleMatches->getTotalHits();
360 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
361 $totalRes +
= $textMatches->getTotalHits();
364 // show number of results and current offset
365 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
366 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
368 $out->addHtml( Xml
::closeElement( 'form' ) );
369 $out->addHtml( "<div class='searchresults'>" );
372 if ( $num ||
$this->offset
) {
373 // Show the create link ahead
374 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
375 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
376 $this->powerSearchOptions() +
array( 'search' => $term ),
377 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
379 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
380 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
382 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
385 $out->parserOptions()->setEditSection( false );
386 if ( $titleMatches ) {
387 if ( $numTitleMatches > 0 ) {
388 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
389 $out->addHTML( $this->showMatches( $titleMatches ) );
391 $titleMatches->free();
393 if ( $textMatches && !$textStatus ) {
394 // output appropriate heading
395 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
396 // if no title matches the heading is redundant
397 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
398 } elseif ( $totalRes == 0 ) {
399 # Don't show the 'no text matches' if we received title matches
400 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
402 // show interwiki results if any
403 if ( $textMatches->hasInterwikiResults() ) {
404 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
407 if ( $numTextMatches > 0 ) {
408 $out->addHTML( $this->showMatches( $textMatches ) );
411 $textMatches->free();
415 $out->addHTML( '<div class="error">' .
416 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
418 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
419 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
420 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
423 $out->addHtml( "</div>" );
425 if ( $num ||
$this->offset
) {
426 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
428 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
433 * @param int $num The number of search results found
434 * @param $titleMatches null|SearchResultSet results from title search
435 * @param $textMatches null|SearchResultSet results from text search
437 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
438 // show direct page/create link if applicable
440 // Check DBkey !== '' in case of fragment link only.
441 if ( is_null( $t ) ||
$t->getDBkey() === '' ||
442 ( $titleMatches !== null && $titleMatches->searchContainedSyntax() ) ||
443 ( $textMatches !== null && $textMatches->searchContainedSyntax() ) ) {
445 // preserve the paragraph for margins etc...
446 $this->getOutput()->addHtml( '<p></p>' );
450 if ( $t->isKnown() ) {
451 $messageName = 'searchmenu-exists';
452 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
453 $messageName = 'searchmenu-new';
455 $messageName = 'searchmenu-new-nocreate';
457 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
458 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
460 // Extensions using the hook might still return an empty $messageName
461 if ( $messageName ) {
462 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
464 // preserve the paragraph for margins etc...
465 $this->getOutput()->addHtml( '<p></p>' );
470 * @param $term string
472 protected function setupPage( $term ) {
473 # Should advanced UI be used?
474 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
475 $out = $this->getOutput();
476 if ( strval( $term ) !== '' ) {
477 $out->setPageTitle( $this->msg( 'searchresults' ) );
478 $out->setHTMLTitle( $this->msg( 'pagetitle' )
479 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
480 ->inContentLanguage()->text()
483 // add javascript specific to special:search
484 $out->addModules( 'mediawiki.special.search' );
488 * Extract "power search" namespace settings from the request object,
489 * returning a list of index numbers to search.
491 * @param $request WebRequest
494 protected function powerSearch( &$request ) {
496 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
497 if ( $request->getCheck( 'ns' . $ns ) ) {
506 * Reconstruct the 'power search' options for links
510 protected function powerSearchOptions() {
512 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
513 if ( $this->profile
!== 'advanced' ) {
514 $opt['profile'] = $this->profile
;
516 foreach ( $this->namespaces
as $n ) {
520 return $opt +
$this->extraParams
;
524 * Show whole set of results
526 * @param $matches SearchResultSet
530 protected function showMatches( &$matches ) {
533 $profile = new ProfileSection( __METHOD__
);
534 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
536 $out = "<ul class='mw-search-results'>\n";
537 $result = $matches->next();
539 $out .= $this->showHit( $result, $terms );
540 $result = $matches->next();
544 // convert the whole thing to desired language variant
545 $out = $wgContLang->convert( $out );
551 * Format a single hit result
553 * @param $result SearchResult
554 * @param array $terms terms to highlight
558 protected function showHit( $result, $terms ) {
559 $profile = new ProfileSection( __METHOD__
);
561 if ( $result->isBrokenTitle() ) {
562 return "<!-- Broken link in search result -->\n";
565 $t = $result->getTitle();
567 $titleSnippet = $result->getTitleSnippet( $terms );
569 if ( $titleSnippet == '' ) {
570 $titleSnippet = null;
575 wfRunHooks( 'ShowSearchHitTitle',
576 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
578 $link = Linker
::linkKnown(
583 //If page content is not readable, just return the title.
584 //This is not quite safe, but better than showing excerpts from non-readable pages
585 //Note that hiding the entry entirely would screw up paging.
586 if ( !$t->userCan( 'read', $this->getUser() ) ) {
587 return "<li>{$link}</li>\n";
590 // If the page doesn't *exist*... our search index is out of date.
591 // The least confusing at this point is to drop the result.
592 // You may get less results, but... oh well. :P
593 if ( $result->isMissingRevision() ) {
594 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
597 // format redirects / relevant sections
598 $redirectTitle = $result->getRedirectTitle();
599 $redirectText = $result->getRedirectSnippet( $terms );
600 $sectionTitle = $result->getSectionTitle();
601 $sectionText = $result->getSectionSnippet( $terms );
604 if ( !is_null( $redirectTitle ) ) {
605 if ( $redirectText == '' ) {
606 $redirectText = null;
609 $redirect = "<span class='searchalttitle'>" .
610 $this->msg( 'search-redirect' )->rawParams(
611 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
617 if ( !is_null( $sectionTitle ) ) {
618 if ( $sectionText == '' ) {
622 $section = "<span class='searchalttitle'>" .
623 $this->msg( 'search-section' )->rawParams(
624 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
628 // format text extract
629 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
631 $lang = $this->getLanguage();
634 if ( is_null( $result->getScore() ) ) {
635 // Search engine doesn't report scoring info
638 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
639 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
643 // format description
644 $byteSize = $result->getByteSize();
645 $wordCount = $result->getWordCount();
646 $timestamp = $result->getTimestamp();
647 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
648 ->numParams( $wordCount )->escaped();
650 if ( $t->getNamespace() == NS_CATEGORY
) {
651 $cat = Category
::newFromTitle( $t );
652 $size = $this->msg( 'search-result-category-size' )
653 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
657 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
659 // link to related articles if supported
661 if ( $result->hasRelated() ) {
662 $st = SpecialPage
::getTitleFor( 'Search' );
663 $stParams = array_merge(
664 $this->powerSearchOptions(),
666 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
667 ':' . $t->getPrefixedText(),
668 'fulltext' => $this->msg( 'search' )->text()
672 $related = ' -- ' . Linker
::linkKnown(
674 $this->msg( 'search-relatedarticle' )->text(),
681 // Include a thumbnail for media files...
682 if ( $t->getNamespace() == NS_FILE
) {
683 $img = $result->getFile();
684 $img = $img ?
: wfFindFile( $t );
685 if ( $result->isFileMatch() ) {
686 $fileMatch = "<span class='searchalttitle'>" .
687 $this->msg( 'search-file-match' )->escaped() . "</span>";
690 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
692 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
693 // Float doesn't seem to interact well with the bullets.
694 // Table messes up vertical alignment of the bullets.
695 // Bullets are therefore disabled (didn't look great anyway).
697 '<table class="searchResultImage">' .
699 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
700 $thumb->toHtml( array( 'desc-link' => true ) ) .
702 '<td style="vertical-align: top;">' .
703 "{$link} {$fileMatch}" .
705 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
716 if ( wfRunHooks( 'ShowSearchHit', array(
717 $this, $result, $terms,
718 &$link, &$redirect, &$section, &$extract,
719 &$score, &$size, &$date, &$related,
722 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
723 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
731 * Show results from other wikis
733 * @param $matches SearchResultSet|array
734 * @param $query String
738 protected function showInterwiki( $matches, $query ) {
740 $profile = new ProfileSection( __METHOD__
);
742 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
743 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
744 $out .= "<ul class='mw-search-iwresults'>\n";
746 // work out custom project captions
747 $customCaptions = array();
748 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
749 foreach ( $customLines as $line ) {
750 $parts = explode( ":", $line, 2 );
751 if ( count( $parts ) == 2 ) { // validate line
752 $customCaptions[$parts[0]] = $parts[1];
757 if ( !is_array( $matches ) ) {
758 $matches = array( $matches );
761 foreach ( $matches as $set ) {
762 $result = $set->next();
764 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
765 $prev = $result->getInterwikiPrefix();
766 $result = $set->next();
771 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
772 $out .= "</ul></div>\n";
774 // convert the whole thing to desired language variant
775 $out = $wgContLang->convert( $out );
781 * Show single interwiki link
783 * @param $result SearchResult
784 * @param $lastInterwiki String
785 * @param $query String
786 * @param array $customCaptions iw prefix -> caption
790 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
791 $profile = new ProfileSection( __METHOD__
);
793 if ( $result->isBrokenTitle() ) {
794 return "<!-- Broken link in search result -->\n";
797 $t = $result->getTitle();
799 $titleSnippet = $result->getTitleSnippet();
801 if ( $titleSnippet == '' ) {
802 $titleSnippet = null;
805 $link = Linker
::linkKnown(
810 // format redirect if any
811 $redirectTitle = $result->getRedirectTitle();
812 $redirectText = $result->getRedirectSnippet();
814 if ( !is_null( $redirectTitle ) ) {
815 if ( $redirectText == '' ) {
816 $redirectText = null;
819 $redirect = "<span class='searchalttitle'>" .
820 $this->msg( 'search-redirect' )->rawParams(
821 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
826 // display project name
827 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
828 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
829 // captions from 'search-interwiki-custom'
830 $caption = $customCaptions[$t->getInterwiki()];
832 // default is to show the hostname of the other wiki which might suck
833 // if there are many wikis on one hostname
834 $parsed = wfParseUrl( $t->getFullURL() );
835 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
837 // "more results" link (special page stuff could be localized, but we might not know target lang)
838 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
839 $searchLink = Linker
::linkKnown(
841 $this->msg( 'search-interwiki-more' )->text(),
845 'fulltext' => 'Search'
848 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
849 {$searchLink}</span>{$caption}</div>\n<ul>";
852 $out .= "<li>{$link} {$redirect}</li>\n";
861 protected function getProfileForm( $profile, $term ) {
864 $opts['redirs'] = $this->searchRedirects
;
865 $opts['profile'] = $this->profile
;
867 if ( $profile === 'advanced' ) {
868 return $this->powerSearchBox( $term, $opts );
871 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
877 * Generates the power search box at [[Special:Search]]
879 * @param string $term search term
881 * @return String: HTML form
883 protected function powerSearchBox( $term, $opts ) {
886 // Groups namespaces into rows according to subject
888 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
889 $subject = MWNamespace
::getSubject( $namespace );
890 if ( !array_key_exists( $subject, $rows ) ) {
891 $rows[$subject] = "";
894 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
896 $name = $this->msg( 'blanknamespace' )->text();
901 'td', array( 'style' => 'white-space: nowrap' )
906 "mw-search-ns{$namespace}",
907 in_array( $namespace, $this->namespaces
)
909 Xml
::closeElement( 'td' );
912 $rows = array_values( $rows );
913 $numRows = count( $rows );
915 // Lays out namespaces in multiple floating two-column tables so they'll
916 // be arranged nicely while still accommodating different screen widths
917 $namespaceTables = '';
918 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
919 $namespaceTables .= Xml
::openElement(
921 array( 'cellpadding' => 0, 'cellspacing' => 0 )
924 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
925 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
928 $namespaceTables .= Xml
::closeElement( 'table' );
931 $showSections = array( 'namespaceTables' => $namespaceTables );
933 // Show redirects check only if backend supports it
934 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
935 $showSections['redirects'] =
936 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
939 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
942 unset( $opts['redirs'] );
943 foreach ( $opts as $key => $value ) {
944 $hidden .= Html
::hidden( $key, $value );
946 // Return final output
947 return Xml
::openElement(
949 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
951 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
952 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
953 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
954 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
955 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
957 Xml
::closeElement( 'fieldset' );
963 protected function getSearchProfiles() {
964 // Builds list of Search Types (profiles)
965 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
969 'message' => 'searchprofile-articles',
970 'tooltip' => 'searchprofile-articles-tooltip',
971 'namespaces' => SearchEngine
::defaultNamespaces(),
972 'namespace-messages' => SearchEngine
::namespacesAsText(
973 SearchEngine
::defaultNamespaces()
977 'message' => 'searchprofile-images',
978 'tooltip' => 'searchprofile-images-tooltip',
979 'namespaces' => array( NS_FILE
),
982 'message' => 'searchprofile-project',
983 'tooltip' => 'searchprofile-project-tooltip',
984 'namespaces' => SearchEngine
::helpNamespaces(),
985 'namespace-messages' => SearchEngine
::namespacesAsText(
986 SearchEngine
::helpNamespaces()
990 'message' => 'searchprofile-everything',
991 'tooltip' => 'searchprofile-everything-tooltip',
992 'namespaces' => $nsAllSet,
995 'message' => 'searchprofile-advanced',
996 'tooltip' => 'searchprofile-advanced-tooltip',
997 'namespaces' => self
::NAMESPACES_CURRENT
,
1001 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1003 foreach ( $profiles as &$data ) {
1004 if ( !is_array( $data['namespaces'] ) ) {
1007 sort( $data['namespaces'] );
1015 * @param $resultsShown
1019 protected function formHeader( $term, $resultsShown, $totalNum ) {
1020 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1023 if ( $this->startsWithImage( $term ) ) {
1025 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1028 $profiles = $this->getSearchProfiles();
1029 $lang = $this->getLanguage();
1031 // Outputs XML for Search Types
1032 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1033 $out .= Xml
::openElement( 'ul' );
1034 foreach ( $profiles as $id => $profile ) {
1035 if ( !isset( $profile['parameters'] ) ) {
1036 $profile['parameters'] = array();
1038 $profile['parameters']['profile'] = $id;
1040 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1041 $lang->commaList( $profile['namespace-messages'] ) : null;
1045 'class' => $this->profile
=== $id ?
'current' : 'normal'
1047 $this->makeSearchLink(
1050 $this->msg( $profile['message'] )->text(),
1051 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1052 $profile['parameters']
1056 $out .= Xml
::closeElement( 'ul' );
1057 $out .= Xml
::closeElement( 'div' );
1060 if ( $resultsShown > 0 ) {
1061 if ( $totalNum > 0 ) {
1062 $top = $this->msg( 'showingresultsheader' )
1063 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1064 ->params( wfEscapeWikiText( $term ) )
1065 ->numParams( $resultsShown )
1067 } elseif ( $resultsShown >= $this->limit
) {
1068 $top = $this->msg( 'showingresults' )
1069 ->numParams( $this->limit
, $this->offset +
1 )
1072 $top = $this->msg( 'showingresultsnum' )
1073 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1076 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1077 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1081 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1082 $out .= Xml
::closeElement( 'div' );
1088 * @param $term string
1091 protected function shortDialog( $term ) {
1092 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1093 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1095 $out .= Html
::input( 'search', $term, 'search', array(
1096 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1099 'class' => 'mw-ui-input',
1101 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1102 $out .= Xml
::submitButton(
1103 $this->msg( 'searchbutton' )->text(),
1104 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1106 return $out . $this->didYouMeanHtml
;
1110 * Make a search link with some target namespaces
1112 * @param $term String
1113 * @param array $namespaces ignored
1114 * @param string $label link's text
1115 * @param string $tooltip link's tooltip
1116 * @param array $params query string parameters
1117 * @return String: HTML fragment
1119 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1121 foreach ( $namespaces as $n ) {
1122 $opt['ns' . $n] = 1;
1124 $opt['redirs'] = $this->searchRedirects
;
1126 $stParams = array_merge(
1129 'fulltext' => $this->msg( 'search' )->text()
1134 return Xml
::element(
1137 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1145 * Check if query starts with image: prefix
1147 * @param string $term the string to check
1150 protected function startsWithImage( $term ) {
1153 $p = explode( ':', $term );
1154 if ( count( $p ) > 1 ) {
1155 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1161 * Check if query starts with all: prefix
1163 * @param string $term the string to check
1166 protected function startsWithAll( $term ) {
1168 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1170 $p = explode( ':', $term );
1171 if ( count( $p ) > 1 ) {
1172 return $p[0] == $allkeyword;
1180 * @return SearchEngine
1182 public function getSearchEngine() {
1183 if ( $this->searchEngine
=== null ) {
1184 $this->searchEngine
= $this->searchEngineType ?
1185 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1187 return $this->searchEngine
;
1191 * Current search profile.
1192 * @return null|string
1194 function getProfile() {
1195 return $this->profile
;
1199 * Current namespaces.
1202 function getNamespaces() {
1203 return $this->namespaces
;
1207 * Users of hook SpecialSearchSetupEngine can use this to
1208 * add more params to links to not lose selection when
1209 * user navigates search results.
1215 public function setExtraParam( $key, $value ) {
1216 $this->extraParams
[$key] = $value;
1219 protected function getGroupName() {