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;
217 wfProfileIn( __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' )
250 wfProfileOut( __METHOD__
);
254 $t = Title
::newFromText( $term );
255 $showSuggestion = $t === null ||
!$t->isKnown();
256 $search->setShowSuggestion( $showSuggestion );
258 // fetch search results
259 $rewritten = $search->replacePrefixes( $term );
261 $titleMatches = $search->searchTitle( $rewritten );
262 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
263 $textMatches = $search->searchText( $rewritten );
267 if ( $textMatches instanceof Status
) {
268 $textStatus = $textMatches;
272 // did you mean... suggestions
273 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
274 $st = SpecialPage
::getTitleFor( 'Search' );
276 # mirror Go/Search behavior of original request ..
277 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
279 if ( $this->fulltext
!= null ) {
280 $didYouMeanParams['fulltext'] = $this->fulltext
;
283 $stParams = array_merge(
285 $this->powerSearchOptions()
288 $suggestionSnippet = $textMatches->getSuggestionSnippet();
290 if ( $suggestionSnippet == '' ) {
291 $suggestionSnippet = null;
294 $suggestLink = Linker
::linkKnown(
301 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
304 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
305 # Hook requested termination
306 wfProfileOut( __METHOD__
);
310 // start rendering the page
315 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
317 'action' => $wgScript
322 # This is an awful awful ID name. It's not a table, but we
323 # named it poorly from when this was a table so now we're
325 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
326 $this->shortDialog( $term ) .
327 Xml
::closeElement( 'div' )
330 // Sometimes the search engine knows there are too many hits
331 if ( $titleMatches instanceof SearchResultTooMany
) {
332 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
333 wfProfileOut( __METHOD__
);
337 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
338 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
339 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
340 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
341 $out->addHTML( '</form>' );
342 // Empty query -- straight view of search form
343 wfProfileOut( __METHOD__
);
347 // Get number of results
348 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
349 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
350 // Total initial query matches (possible false positives)
351 $num = $titleMatchesNum +
$textMatchesNum;
353 // Get total actual results (after second filtering, if any)
354 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
355 $titleMatches->getTotalHits() : $titleMatchesNum;
356 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
357 $textMatches->getTotalHits() : $textMatchesNum;
359 // get total number of results if backend can calculate it
361 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
362 $totalRes +
= $titleMatches->getTotalHits();
364 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
365 $totalRes +
= $textMatches->getTotalHits();
368 // show number of results and current offset
369 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
370 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
372 $out->addHtml( Xml
::closeElement( 'form' ) );
373 $out->addHtml( "<div class='searchresults'>" );
376 if ( $num ||
$this->offset
) {
377 // Show the create link ahead
378 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
379 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
380 $this->powerSearchOptions() +
array( 'search' => $term ),
381 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
383 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
384 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
386 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
389 $out->parserOptions()->setEditSection( false );
390 if ( $titleMatches ) {
391 if ( $numTitleMatches > 0 ) {
392 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
393 $out->addHTML( $this->showMatches( $titleMatches ) );
395 $titleMatches->free();
397 if ( $textMatches && !$textStatus ) {
398 // output appropriate heading
399 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
400 // if no title matches the heading is redundant
401 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
402 } elseif ( $totalRes == 0 ) {
403 # Don't show the 'no text matches' if we received title matches
404 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
406 // show interwiki results if any
407 if ( $textMatches->hasInterwikiResults() ) {
408 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
411 if ( $numTextMatches > 0 ) {
412 $out->addHTML( $this->showMatches( $textMatches ) );
415 $textMatches->free();
419 $out->addHTML( '<div class="error">' .
420 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
422 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
423 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
424 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
427 $out->addHtml( "</div>" );
429 if ( $num ||
$this->offset
) {
430 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
432 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
433 wfProfileOut( __METHOD__
);
438 * @param int $num The number of search results found
439 * @param $titleMatches null|SearchResultSet results from title search
440 * @param $textMatches null|SearchResultSet results from text search
442 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
443 // show direct page/create link if applicable
445 // Check DBkey !== '' in case of fragment link only.
446 if ( is_null( $t ) ||
$t->getDBkey() === '' ||
447 ( $titleMatches !== null && $titleMatches->searchContainedSyntax() ) ||
448 ( $textMatches !== null && $textMatches->searchContainedSyntax() ) ) {
450 // preserve the paragraph for margins etc...
451 $this->getOutput()->addHtml( '<p></p>' );
455 if ( $t->isKnown() ) {
456 $messageName = 'searchmenu-exists';
457 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
458 $messageName = 'searchmenu-new';
460 $messageName = 'searchmenu-new-nocreate';
462 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
463 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
465 // Extensions using the hook might still return an empty $messageName
466 if ( $messageName ) {
467 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
469 // preserve the paragraph for margins etc...
470 $this->getOutput()->addHtml( '<p></p>' );
475 * @param $term string
477 protected function setupPage( $term ) {
478 # Should advanced UI be used?
479 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
480 $out = $this->getOutput();
481 if ( strval( $term ) !== '' ) {
482 $out->setPageTitle( $this->msg( 'searchresults' ) );
483 $out->setHTMLTitle( $this->msg( 'pagetitle' )
484 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
485 ->inContentLanguage()->text()
488 // add javascript specific to special:search
489 $out->addModules( 'mediawiki.special.search' );
493 * Extract "power search" namespace settings from the request object,
494 * returning a list of index numbers to search.
496 * @param $request WebRequest
499 protected function powerSearch( &$request ) {
501 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
502 if ( $request->getCheck( 'ns' . $ns ) ) {
511 * Reconstruct the 'power search' options for links
515 protected function powerSearchOptions() {
517 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
518 if ( $this->profile
!== 'advanced' ) {
519 $opt['profile'] = $this->profile
;
521 foreach ( $this->namespaces
as $n ) {
525 return $opt +
$this->extraParams
;
529 * Show whole set of results
531 * @param $matches SearchResultSet
535 protected function showMatches( &$matches ) {
537 wfProfileIn( __METHOD__
);
539 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
542 $infoLine = $matches->getInfo();
543 if ( !is_null( $infoLine ) ) {
544 $out .= "\n<!-- {$infoLine} -->\n";
546 $out .= "<ul class='mw-search-results'>\n";
547 $result = $matches->next();
549 $out .= $this->showHit( $result, $terms );
550 $result = $matches->next();
554 // convert the whole thing to desired language variant
555 $out = $wgContLang->convert( $out );
556 wfProfileOut( __METHOD__
);
561 * Format a single hit result
563 * @param $result SearchResult
564 * @param array $terms terms to highlight
568 protected function showHit( $result, $terms ) {
569 wfProfileIn( __METHOD__
);
571 if ( $result->isBrokenTitle() ) {
572 wfProfileOut( __METHOD__
);
573 return "<!-- Broken link in search result -->\n";
576 $t = $result->getTitle();
578 $titleSnippet = $result->getTitleSnippet( $terms );
580 if ( $titleSnippet == '' ) {
581 $titleSnippet = null;
586 wfRunHooks( 'ShowSearchHitTitle',
587 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
589 $link = Linker
::linkKnown(
594 //If page content is not readable, just return the title.
595 //This is not quite safe, but better than showing excerpts from non-readable pages
596 //Note that hiding the entry entirely would screw up paging.
597 if ( !$t->userCan( 'read', $this->getUser() ) ) {
598 wfProfileOut( __METHOD__
);
599 return "<li>{$link}</li>\n";
602 // If the page doesn't *exist*... our search index is out of date.
603 // The least confusing at this point is to drop the result.
604 // You may get less results, but... oh well. :P
605 if ( $result->isMissingRevision() ) {
606 wfProfileOut( __METHOD__
);
607 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
610 // format redirects / relevant sections
611 $redirectTitle = $result->getRedirectTitle();
612 $redirectText = $result->getRedirectSnippet( $terms );
613 $sectionTitle = $result->getSectionTitle();
614 $sectionText = $result->getSectionSnippet( $terms );
617 if ( !is_null( $redirectTitle ) ) {
618 if ( $redirectText == '' ) {
619 $redirectText = null;
622 $redirect = "<span class='searchalttitle'>" .
623 $this->msg( 'search-redirect' )->rawParams(
624 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
630 if ( !is_null( $sectionTitle ) ) {
631 if ( $sectionText == '' ) {
635 $section = "<span class='searchalttitle'>" .
636 $this->msg( 'search-section' )->rawParams(
637 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
641 // format text extract
642 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
644 $lang = $this->getLanguage();
647 if ( is_null( $result->getScore() ) ) {
648 // Search engine doesn't report scoring info
651 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
652 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
656 // format description
657 $byteSize = $result->getByteSize();
658 $wordCount = $result->getWordCount();
659 $timestamp = $result->getTimestamp();
660 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
661 ->numParams( $wordCount )->escaped();
663 if ( $t->getNamespace() == NS_CATEGORY
) {
664 $cat = Category
::newFromTitle( $t );
665 $size = $this->msg( 'search-result-category-size' )
666 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
670 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
672 // link to related articles if supported
674 if ( $result->hasRelated() ) {
675 $st = SpecialPage
::getTitleFor( 'Search' );
676 $stParams = array_merge(
677 $this->powerSearchOptions(),
679 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
680 ':' . $t->getPrefixedText(),
681 'fulltext' => $this->msg( 'search' )->text()
685 $related = ' -- ' . Linker
::linkKnown(
687 $this->msg( 'search-relatedarticle' )->text(),
694 // Include a thumbnail for media files...
695 if ( $t->getNamespace() == NS_FILE
) {
696 $img = $result->getFile();
697 $img = $img ?
: wfFindFile( $t );
698 if ( $result->isFileMatch() ) {
699 $fileMatch = "<span class='searchalttitle'>" .
700 $this->msg( 'search-file-match' )->escaped() . "</span>";
703 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
705 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
706 wfProfileOut( __METHOD__
);
707 // Float doesn't seem to interact well with the bullets.
708 // Table messes up vertical alignment of the bullets.
709 // Bullets are therefore disabled (didn't look great anyway).
711 '<table class="searchResultImage">' .
713 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
714 $thumb->toHtml( array( 'desc-link' => true ) ) .
716 '<td style="vertical-align: top;">' .
717 "{$link} {$fileMatch}" .
719 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
730 if ( wfRunHooks( 'ShowSearchHit', array(
731 $this, $result, $terms,
732 &$link, &$redirect, &$section, &$extract,
733 &$score, &$size, &$date, &$related,
736 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
737 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
741 wfProfileOut( __METHOD__
);
746 * Show results from other wikis
748 * @param $matches SearchResultSet
749 * @param $query String
753 protected function showInterwiki( $matches, $query ) {
755 wfProfileIn( __METHOD__
);
756 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
758 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
759 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
760 $out .= "<ul class='mw-search-iwresults'>\n";
762 // work out custom project captions
763 $customCaptions = array();
764 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
765 foreach ( $customLines as $line ) {
766 $parts = explode( ":", $line, 2 );
767 if ( count( $parts ) == 2 ) { // validate line
768 $customCaptions[$parts[0]] = $parts[1];
773 $result = $matches->next();
775 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
776 $prev = $result->getInterwikiPrefix();
777 $result = $matches->next();
779 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
780 $out .= "</ul></div>\n";
782 // convert the whole thing to desired language variant
783 $out = $wgContLang->convert( $out );
784 wfProfileOut( __METHOD__
);
789 * Show single interwiki link
791 * @param $result SearchResult
792 * @param $lastInterwiki String
793 * @param $terms Array
794 * @param $query String
795 * @param array $customCaptions iw prefix -> caption
799 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
800 wfProfileIn( __METHOD__
);
802 if ( $result->isBrokenTitle() ) {
803 wfProfileOut( __METHOD__
);
804 return "<!-- Broken link in search result -->\n";
807 $t = $result->getTitle();
809 $titleSnippet = $result->getTitleSnippet();
811 if ( $titleSnippet == '' ) {
812 $titleSnippet = null;
815 $link = Linker
::linkKnown(
820 // format redirect if any
821 $redirectTitle = $result->getRedirectTitle();
822 $redirectText = $result->getRedirectSnippet();
824 if ( !is_null( $redirectTitle ) ) {
825 if ( $redirectText == '' ) {
826 $redirectText = null;
829 $redirect = "<span class='searchalttitle'>" .
830 $this->msg( 'search-redirect' )->rawParams(
831 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
836 // display project name
837 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
838 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
839 // captions from 'search-interwiki-custom'
840 $caption = $customCaptions[$t->getInterwiki()];
842 // default is to show the hostname of the other wiki which might suck
843 // if there are many wikis on one hostname
844 $parsed = wfParseUrl( $t->getFullURL() );
845 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
847 // "more results" link (special page stuff could be localized, but we might not know target lang)
848 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
849 $searchLink = Linker
::linkKnown(
851 $this->msg( 'search-interwiki-more' )->text(),
855 'fulltext' => 'Search'
858 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
859 {$searchLink}</span>{$caption}</div>\n<ul>";
862 $out .= "<li>{$link} {$redirect}</li>\n";
863 wfProfileOut( __METHOD__
);
872 protected function getProfileForm( $profile, $term ) {
875 $opts['redirs'] = $this->searchRedirects
;
876 $opts['profile'] = $this->profile
;
878 if ( $profile === 'advanced' ) {
879 return $this->powerSearchBox( $term, $opts );
882 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
888 * Generates the power search box at [[Special:Search]]
890 * @param string $term search term
892 * @return String: HTML form
894 protected function powerSearchBox( $term, $opts ) {
897 // Groups namespaces into rows according to subject
899 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
900 $subject = MWNamespace
::getSubject( $namespace );
901 if ( !array_key_exists( $subject, $rows ) ) {
902 $rows[$subject] = "";
905 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
907 $name = $this->msg( 'blanknamespace' )->text();
912 'td', array( 'style' => 'white-space: nowrap' )
917 "mw-search-ns{$namespace}",
918 in_array( $namespace, $this->namespaces
)
920 Xml
::closeElement( 'td' );
923 $rows = array_values( $rows );
924 $numRows = count( $rows );
926 // Lays out namespaces in multiple floating two-column tables so they'll
927 // be arranged nicely while still accommodating different screen widths
928 $namespaceTables = '';
929 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
930 $namespaceTables .= Xml
::openElement(
932 array( 'cellpadding' => 0, 'cellspacing' => 0 )
935 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
936 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
939 $namespaceTables .= Xml
::closeElement( 'table' );
942 $showSections = array( 'namespaceTables' => $namespaceTables );
944 // Show redirects check only if backend supports it
945 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
946 $showSections['redirects'] =
947 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
950 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
953 unset( $opts['redirs'] );
954 foreach ( $opts as $key => $value ) {
955 $hidden .= Html
::hidden( $key, $value );
957 // Return final output
958 return Xml
::openElement(
960 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
962 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
963 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
964 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
965 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
966 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
968 Xml
::closeElement( 'fieldset' );
974 protected function getSearchProfiles() {
975 // Builds list of Search Types (profiles)
976 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
980 'message' => 'searchprofile-articles',
981 'tooltip' => 'searchprofile-articles-tooltip',
982 'namespaces' => SearchEngine
::defaultNamespaces(),
983 'namespace-messages' => SearchEngine
::namespacesAsText(
984 SearchEngine
::defaultNamespaces()
988 'message' => 'searchprofile-images',
989 'tooltip' => 'searchprofile-images-tooltip',
990 'namespaces' => array( NS_FILE
),
993 'message' => 'searchprofile-project',
994 'tooltip' => 'searchprofile-project-tooltip',
995 'namespaces' => SearchEngine
::helpNamespaces(),
996 'namespace-messages' => SearchEngine
::namespacesAsText(
997 SearchEngine
::helpNamespaces()
1001 'message' => 'searchprofile-everything',
1002 'tooltip' => 'searchprofile-everything-tooltip',
1003 'namespaces' => $nsAllSet,
1005 'advanced' => array(
1006 'message' => 'searchprofile-advanced',
1007 'tooltip' => 'searchprofile-advanced-tooltip',
1008 'namespaces' => self
::NAMESPACES_CURRENT
,
1012 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1014 foreach ( $profiles as &$data ) {
1015 if ( !is_array( $data['namespaces'] ) ) {
1018 sort( $data['namespaces'] );
1026 * @param $resultsShown
1030 protected function formHeader( $term, $resultsShown, $totalNum ) {
1031 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1034 if ( $this->startsWithImage( $term ) ) {
1036 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1039 $profiles = $this->getSearchProfiles();
1040 $lang = $this->getLanguage();
1042 // Outputs XML for Search Types
1043 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1044 $out .= Xml
::openElement( 'ul' );
1045 foreach ( $profiles as $id => $profile ) {
1046 if ( !isset( $profile['parameters'] ) ) {
1047 $profile['parameters'] = array();
1049 $profile['parameters']['profile'] = $id;
1051 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1052 $lang->commaList( $profile['namespace-messages'] ) : null;
1056 'class' => $this->profile
=== $id ?
'current' : 'normal'
1058 $this->makeSearchLink(
1061 $this->msg( $profile['message'] )->text(),
1062 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1063 $profile['parameters']
1067 $out .= Xml
::closeElement( 'ul' );
1068 $out .= Xml
::closeElement( 'div' );
1071 if ( $resultsShown > 0 ) {
1072 if ( $totalNum > 0 ) {
1073 $top = $this->msg( 'showingresultsheader' )
1074 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1075 ->params( wfEscapeWikiText( $term ) )
1076 ->numParams( $resultsShown )
1078 } elseif ( $resultsShown >= $this->limit
) {
1079 $top = $this->msg( 'showingresults' )
1080 ->numParams( $this->limit
, $this->offset +
1 )
1083 $top = $this->msg( 'showingresultsnum' )
1084 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1087 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1088 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1092 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1093 $out .= Xml
::closeElement( 'div' );
1099 * @param $term string
1102 protected function shortDialog( $term ) {
1103 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1104 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1106 $out .= Html
::input( 'search', $term, 'search', array(
1107 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1110 'class' => 'mw-ui-input',
1112 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1113 $out .= Xml
::submitButton(
1114 $this->msg( 'searchbutton' )->text(),
1115 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1117 return $out . $this->didYouMeanHtml
;
1121 * Make a search link with some target namespaces
1123 * @param $term String
1124 * @param array $namespaces ignored
1125 * @param string $label link's text
1126 * @param string $tooltip link's tooltip
1127 * @param array $params query string parameters
1128 * @return String: HTML fragment
1130 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1132 foreach ( $namespaces as $n ) {
1133 $opt['ns' . $n] = 1;
1135 $opt['redirs'] = $this->searchRedirects
;
1137 $stParams = array_merge(
1140 'fulltext' => $this->msg( 'search' )->text()
1145 return Xml
::element(
1148 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1156 * Check if query starts with image: prefix
1158 * @param string $term the string to check
1161 protected function startsWithImage( $term ) {
1164 $p = explode( ':', $term );
1165 if ( count( $p ) > 1 ) {
1166 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1172 * Check if query starts with all: prefix
1174 * @param string $term the string to check
1177 protected function startsWithAll( $term ) {
1179 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1181 $p = explode( ':', $term );
1182 if ( count( $p ) > 1 ) {
1183 return $p[0] == $allkeyword;
1191 * @return SearchEngine
1193 public function getSearchEngine() {
1194 if ( $this->searchEngine
=== null ) {
1195 $this->searchEngine
= $this->searchEngineType ?
1196 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1198 return $this->searchEngine
;
1202 * Current search profile.
1203 * @return null|string
1205 function getProfile() {
1206 return $this->profile
;
1210 * Current namespaces.
1213 function getNamespaces() {
1214 return $this->namespaces
;
1218 * Users of hook SpecialSearchSetupEngine can use this to
1219 * add more params to links to not lose selection when
1220 * user navigates search results.
1226 public function setExtraParam( $key, $value ) {
1227 $this->extraParams
[$key] = $value;
1230 protected function getGroupName() {