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' ) )
108 ||
!is_null( $request->getVal( 'searchx' ) )
110 $this->showResults( $search );
112 $this->goResult( $search );
117 * Set up basic search parameters from the request and user settings.
119 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
121 public function load() {
122 $request = $this->getRequest();
123 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '', 500 );
124 $this->mPrefix
= $request->getVal( 'prefix', '' );
126 $user = $this->getUser();
128 # Extract manually requested namespaces
129 $nslist = $this->powerSearch( $request );
130 if ( !count( $nslist ) ) {
131 # Fallback to user preference
132 $nslist = SearchEngine
::userNamespaces( $user );
136 if ( !count( $nslist ) ) {
137 $profile = 'default';
140 $profile = $request->getVal( 'profile', $profile );
141 $profiles = $this->getSearchProfiles();
142 if ( $profile === null ) {
143 // BC with old request format
144 $profile = 'advanced';
145 foreach ( $profiles as $key => $data ) {
146 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
150 $this->namespaces
= $nslist;
151 } elseif ( $profile === 'advanced' ) {
152 $this->namespaces
= $nslist;
154 if ( isset( $profiles[$profile]['namespaces'] ) ) {
155 $this->namespaces
= $profiles[$profile]['namespaces'];
157 // Unknown profile requested
158 $profile = 'default';
159 $this->namespaces
= $profiles['default']['namespaces'];
163 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
164 $default = $request->getBool( 'profile' ) ?
0 : 1;
165 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
166 $this->didYouMeanHtml
= ''; # html of did you mean... link
167 $this->fulltext
= $request->getVal( 'fulltext' );
168 $this->profile
= $profile;
172 * If an exact title match can be found, jump straight ahead to it.
174 * @param $term String
176 public function goResult( $term ) {
177 $this->setupPage( $term );
178 # Try to go to page as entered.
179 $t = Title
::newFromText( $term );
180 # If the string cannot be used to create a title
181 if ( is_null( $t ) ) {
182 $this->showResults( $term );
185 # If there's an exact or very near match, jump right there.
186 $t = SearchEngine
::getNearMatch( $term );
188 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
189 # Hook requested termination
193 if ( !is_null( $t ) ) {
194 $this->getOutput()->redirect( $t->getFullURL() );
197 # No match, generate an edit URL
198 $t = Title
::newFromText( $term );
199 if ( !is_null( $t ) ) {
201 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
202 wfDebugLog( 'nogomatch', $t->getText(), 'private' );
204 # If the feature is enabled, go straight to the edit page
206 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
210 $this->showResults( $term );
214 * @param $term String
216 public function showResults( $term ) {
217 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
218 wfProfileIn( __METHOD__
);
220 $search = $this->getSearchEngine();
221 $search->setLimitOffset( $this->limit
, $this->offset
);
222 $search->setNamespaces( $this->namespaces
);
223 $search->showRedirects
= $this->searchRedirects
; // BC
224 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
225 $search->prefix
= $this->mPrefix
;
226 $term = $search->transformSearchTerm( $term );
228 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
230 $this->setupPage( $term );
232 $out = $this->getOutput();
234 if ( $wgDisableTextSearch ) {
235 if ( $wgSearchForwardUrl ) {
236 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
237 $out->redirect( $url );
240 Xml
::openElement( 'fieldset' ) .
241 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
242 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
243 $this->msg( 'googlesearch' )->rawParams(
244 htmlspecialchars( $term ),
246 $this->msg( 'searchbutton' )->escaped()
248 Xml
::closeElement( 'fieldset' )
251 wfProfileOut( __METHOD__
);
255 $t = Title
::newFromText( $term );
256 $showSuggestion = $t === null ||
!$t->isKnown();
257 $search->setShowSuggestion( $showSuggestion );
259 // fetch search results
260 $rewritten = $search->replacePrefixes( $term );
262 $titleMatches = $search->searchTitle( $rewritten );
263 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
264 $textMatches = $search->searchText( $rewritten );
268 if ( $textMatches instanceof Status
) {
269 $textStatus = $textMatches;
273 // did you mean... suggestions
274 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
275 $st = SpecialPage
::getTitleFor( 'Search' );
277 # mirror Go/Search behavior of original request ..
278 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
280 if ( $this->fulltext
!= null ) {
281 $didYouMeanParams['fulltext'] = $this->fulltext
;
284 $stParams = array_merge(
286 $this->powerSearchOptions()
289 $suggestionSnippet = $textMatches->getSuggestionSnippet();
291 if ( $suggestionSnippet == '' ) {
292 $suggestionSnippet = null;
295 $suggestLink = Linker
::linkKnown(
302 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
305 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
306 # Hook requested termination
307 wfProfileOut( __METHOD__
);
311 // start rendering the page
316 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
318 'action' => $wgScript
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
326 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
327 $this->shortDialog( $term ) .
328 Xml
::closeElement( 'div' )
331 // Sometimes the search engine knows there are too many hits
332 if ( $titleMatches instanceof SearchResultTooMany
) {
333 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
334 wfProfileOut( __METHOD__
);
338 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
339 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
340 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
341 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
342 $out->addHTML( '</form>' );
343 // Empty query -- straight view of search form
344 wfProfileOut( __METHOD__
);
348 // Get number of results
349 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
350 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
351 // Total initial query matches (possible false positives)
352 $num = $titleMatchesNum +
$textMatchesNum;
354 // Get total actual results (after second filtering, if any)
355 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
356 $titleMatches->getTotalHits() : $titleMatchesNum;
357 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
358 $textMatches->getTotalHits() : $textMatchesNum;
360 // get total number of results if backend can calculate it
362 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
363 $totalRes +
= $titleMatches->getTotalHits();
365 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
366 $totalRes +
= $textMatches->getTotalHits();
369 // show number of results and current offset
370 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
371 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
373 $out->addHtml( Xml
::closeElement( 'form' ) );
374 $out->addHtml( "<div class='searchresults'>" );
377 if ( $num ||
$this->offset
) {
378 // Show the create link ahead
379 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
380 $prevnext = $this->getLanguage()->viewPrevNext( $this->getPageTitle(), $this->offset
, $this->limit
,
381 $this->powerSearchOptions() +
array( 'search' => $term ),
382 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
384 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
385 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
387 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
390 $out->parserOptions()->setEditSection( false );
391 if ( $titleMatches ) {
392 if ( $numTitleMatches > 0 ) {
393 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
394 $out->addHTML( $this->showMatches( $titleMatches ) );
396 $titleMatches->free();
398 if ( $textMatches && !$textStatus ) {
399 // output appropriate heading
400 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
401 // if no title matches the heading is redundant
402 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
403 } elseif ( $totalRes == 0 ) {
404 # Don't show the 'no text matches' if we received title matches
405 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
407 // show interwiki results if any
408 if ( $textMatches->hasInterwikiResults() ) {
409 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
412 if ( $numTextMatches > 0 ) {
413 $out->addHTML( $this->showMatches( $textMatches ) );
416 $textMatches->free();
420 $out->addHTML( '<div class="error">' .
421 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
423 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
424 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
425 $this->showCreateLink( $t, $num, $titleMatches, $textMatches );
428 $out->addHtml( "</div>" );
430 if ( $num ||
$this->offset
) {
431 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
433 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
434 wfProfileOut( __METHOD__
);
439 * @param int $num The number of search results found
440 * @param $titleMatches null|SearchResultSet results from title search
441 * @param $textMatches null|SearchResultSet results from text search
443 protected function showCreateLink( $t, $num, $titleMatches, $textMatches ) {
444 // show direct page/create link if applicable
446 // Check DBkey !== '' in case of fragment link only.
447 if ( is_null( $t ) ||
$t->getDBkey() === '' ||
448 ( $titleMatches !== null && $titleMatches->searchContainedSyntax() ) ||
449 ( $textMatches !== null && $textMatches->searchContainedSyntax() ) ) {
451 // preserve the paragraph for margins etc...
452 $this->getOutput()->addHtml( '<p></p>' );
456 if ( $t->isKnown() ) {
457 $messageName = 'searchmenu-exists';
458 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
459 $messageName = 'searchmenu-new';
461 $messageName = 'searchmenu-new-nocreate';
463 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ), Message
::numParam( $num ) );
464 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
466 // Extensions using the hook might still return an empty $messageName
467 if ( $messageName ) {
468 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
470 // preserve the paragraph for margins etc...
471 $this->getOutput()->addHtml( '<p></p>' );
476 * @param $term string
478 protected function setupPage( $term ) {
479 # Should advanced UI be used?
480 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
481 $out = $this->getOutput();
482 if ( strval( $term ) !== '' ) {
483 $out->setPageTitle( $this->msg( 'searchresults' ) );
484 $out->setHTMLTitle( $this->msg( 'pagetitle' )
485 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
486 ->inContentLanguage()->text()
489 // add javascript specific to special:search
490 $out->addModules( 'mediawiki.special.search' );
494 * Extract "power search" namespace settings from the request object,
495 * returning a list of index numbers to search.
497 * @param $request WebRequest
500 protected function powerSearch( &$request ) {
502 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
503 if ( $request->getCheck( 'ns' . $ns ) ) {
512 * Reconstruct the 'power search' options for links
516 protected function powerSearchOptions() {
518 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
519 if ( $this->profile
!== 'advanced' ) {
520 $opt['profile'] = $this->profile
;
522 foreach ( $this->namespaces
as $n ) {
526 return $opt +
$this->extraParams
;
530 * Show whole set of results
532 * @param $matches SearchResultSet
536 protected function showMatches( &$matches ) {
538 wfProfileIn( __METHOD__
);
540 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
543 $infoLine = $matches->getInfo();
544 if ( !is_null( $infoLine ) ) {
545 $out .= "\n<!-- {$infoLine} -->\n";
547 $out .= "<ul class='mw-search-results'>\n";
548 $result = $matches->next();
550 $out .= $this->showHit( $result, $terms );
551 $result = $matches->next();
555 // convert the whole thing to desired language variant
556 $out = $wgContLang->convert( $out );
557 wfProfileOut( __METHOD__
);
562 * Format a single hit result
564 * @param $result SearchResult
565 * @param array $terms terms to highlight
569 protected function showHit( $result, $terms ) {
570 wfProfileIn( __METHOD__
);
572 if ( $result->isBrokenTitle() ) {
573 wfProfileOut( __METHOD__
);
574 return "<!-- Broken link in search result -->\n";
577 $t = $result->getTitle();
579 $titleSnippet = $result->getTitleSnippet( $terms );
581 if ( $titleSnippet == '' ) {
582 $titleSnippet = null;
587 wfRunHooks( 'ShowSearchHitTitle',
588 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
590 $link = Linker
::linkKnown(
595 //If page content is not readable, just return the title.
596 //This is not quite safe, but better than showing excerpts from non-readable pages
597 //Note that hiding the entry entirely would screw up paging.
598 if ( !$t->userCan( 'read', $this->getUser() ) ) {
599 wfProfileOut( __METHOD__
);
600 return "<li>{$link}</li>\n";
603 // If the page doesn't *exist*... our search index is out of date.
604 // The least confusing at this point is to drop the result.
605 // You may get less results, but... oh well. :P
606 if ( $result->isMissingRevision() ) {
607 wfProfileOut( __METHOD__
);
608 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
611 // format redirects / relevant sections
612 $redirectTitle = $result->getRedirectTitle();
613 $redirectText = $result->getRedirectSnippet( $terms );
614 $sectionTitle = $result->getSectionTitle();
615 $sectionText = $result->getSectionSnippet( $terms );
618 if ( !is_null( $redirectTitle ) ) {
619 if ( $redirectText == '' ) {
620 $redirectText = null;
623 $redirect = "<span class='searchalttitle'>" .
624 $this->msg( 'search-redirect' )->rawParams(
625 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
631 if ( !is_null( $sectionTitle ) ) {
632 if ( $sectionText == '' ) {
636 $section = "<span class='searchalttitle'>" .
637 $this->msg( 'search-section' )->rawParams(
638 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
642 // format text extract
643 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
645 $lang = $this->getLanguage();
648 if ( is_null( $result->getScore() ) ) {
649 // Search engine doesn't report scoring info
652 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
653 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
657 // format description
658 $byteSize = $result->getByteSize();
659 $wordCount = $result->getWordCount();
660 $timestamp = $result->getTimestamp();
661 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
662 ->numParams( $wordCount )->escaped();
664 if ( $t->getNamespace() == NS_CATEGORY
) {
665 $cat = Category
::newFromTitle( $t );
666 $size = $this->msg( 'search-result-category-size' )
667 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
671 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
673 // link to related articles if supported
675 if ( $result->hasRelated() ) {
676 $st = SpecialPage
::getTitleFor( 'Search' );
677 $stParams = array_merge(
678 $this->powerSearchOptions(),
680 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
681 ':' . $t->getPrefixedText(),
682 'fulltext' => $this->msg( 'search' )->text()
686 $related = ' -- ' . Linker
::linkKnown(
688 $this->msg( 'search-relatedarticle' )->text(),
695 // Include a thumbnail for media files...
696 if ( $t->getNamespace() == NS_FILE
) {
697 $img = $result->getFile();
698 $img = $img ?
: wfFindFile( $t );
699 if ( $result->isFileMatch() ) {
700 $fileMatch = "<span class='searchalttitle'>" .
701 $this->msg( 'search-file-match' )->escaped() . "</span>";
704 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
706 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
707 wfProfileOut( __METHOD__
);
708 // Float doesn't seem to interact well with the bullets.
709 // Table messes up vertical alignment of the bullets.
710 // Bullets are therefore disabled (didn't look great anyway).
712 '<table class="searchResultImage">' .
714 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
715 $thumb->toHtml( array( 'desc-link' => true ) ) .
717 '<td style="vertical-align: top;">' .
718 "{$link} {$fileMatch}" .
720 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
731 if ( wfRunHooks( 'ShowSearchHit', array(
732 $this, $result, $terms,
733 &$link, &$redirect, &$section, &$extract,
734 &$score, &$size, &$date, &$related,
737 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
738 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
742 wfProfileOut( __METHOD__
);
747 * Show results from other wikis
749 * @param $matches SearchResultSet
750 * @param $query String
754 protected function showInterwiki( $matches, $query ) {
756 wfProfileIn( __METHOD__
);
757 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
759 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
760 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
761 $out .= "<ul class='mw-search-iwresults'>\n";
763 // work out custom project captions
764 $customCaptions = array();
765 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
766 foreach ( $customLines as $line ) {
767 $parts = explode( ":", $line, 2 );
768 if ( count( $parts ) == 2 ) { // validate line
769 $customCaptions[$parts[0]] = $parts[1];
774 $result = $matches->next();
776 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
777 $prev = $result->getInterwikiPrefix();
778 $result = $matches->next();
780 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
781 $out .= "</ul></div>\n";
783 // convert the whole thing to desired language variant
784 $out = $wgContLang->convert( $out );
785 wfProfileOut( __METHOD__
);
790 * Show single interwiki link
792 * @param $result SearchResult
793 * @param $lastInterwiki String
794 * @param $terms Array
795 * @param $query String
796 * @param array $customCaptions iw prefix -> caption
800 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
801 wfProfileIn( __METHOD__
);
803 if ( $result->isBrokenTitle() ) {
804 wfProfileOut( __METHOD__
);
805 return "<!-- Broken link in search result -->\n";
808 $t = $result->getTitle();
810 $titleSnippet = $result->getTitleSnippet( $terms );
812 if ( $titleSnippet == '' ) {
813 $titleSnippet = null;
816 $link = Linker
::linkKnown(
821 // format redirect if any
822 $redirectTitle = $result->getRedirectTitle();
823 $redirectText = $result->getRedirectSnippet( $terms );
825 if ( !is_null( $redirectTitle ) ) {
826 if ( $redirectText == '' ) {
827 $redirectText = null;
830 $redirect = "<span class='searchalttitle'>" .
831 $this->msg( 'search-redirect' )->rawParams(
832 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
837 // display project name
838 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
839 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
840 // captions from 'search-interwiki-custom'
841 $caption = $customCaptions[$t->getInterwiki()];
843 // default is to show the hostname of the other wiki which might suck
844 // if there are many wikis on one hostname
845 $parsed = wfParseUrl( $t->getFullURL() );
846 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
848 // "more results" link (special page stuff could be localized, but we might not know target lang)
849 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
850 $searchLink = Linker
::linkKnown(
852 $this->msg( 'search-interwiki-more' )->text(),
856 'fulltext' => 'Search'
859 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
860 {$searchLink}</span>{$caption}</div>\n<ul>";
863 $out .= "<li>{$link} {$redirect}</li>\n";
864 wfProfileOut( __METHOD__
);
873 protected function getProfileForm( $profile, $term ) {
876 $opts['redirs'] = $this->searchRedirects
;
877 $opts['profile'] = $this->profile
;
879 if ( $profile === 'advanced' ) {
880 return $this->powerSearchBox( $term, $opts );
883 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
889 * Generates the power search box at [[Special:Search]]
891 * @param string $term search term
893 * @return String: HTML form
895 protected function powerSearchBox( $term, $opts ) {
898 // Groups namespaces into rows according to subject
900 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
901 $subject = MWNamespace
::getSubject( $namespace );
902 if ( !array_key_exists( $subject, $rows ) ) {
903 $rows[$subject] = "";
906 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
908 $name = $this->msg( 'blanknamespace' )->text();
913 'td', array( 'style' => 'white-space: nowrap' )
918 "mw-search-ns{$namespace}",
919 in_array( $namespace, $this->namespaces
)
921 Xml
::closeElement( 'td' );
924 $rows = array_values( $rows );
925 $numRows = count( $rows );
927 // Lays out namespaces in multiple floating two-column tables so they'll
928 // be arranged nicely while still accommodating different screen widths
929 $namespaceTables = '';
930 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
931 $namespaceTables .= Xml
::openElement(
933 array( 'cellpadding' => 0, 'cellspacing' => 0 )
936 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
937 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
940 $namespaceTables .= Xml
::closeElement( 'table' );
943 $showSections = array( 'namespaceTables' => $namespaceTables );
945 // Show redirects check only if backend supports it
946 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
947 $showSections['redirects'] =
948 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
951 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
954 unset( $opts['redirs'] );
955 foreach ( $opts as $key => $value ) {
956 $hidden .= Html
::hidden( $key, $value );
958 // Return final output
959 return Xml
::openElement(
961 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
963 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
964 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
965 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
966 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
967 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
969 Xml
::closeElement( 'fieldset' );
975 protected function getSearchProfiles() {
976 // Builds list of Search Types (profiles)
977 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
981 'message' => 'searchprofile-articles',
982 'tooltip' => 'searchprofile-articles-tooltip',
983 'namespaces' => SearchEngine
::defaultNamespaces(),
984 'namespace-messages' => SearchEngine
::namespacesAsText(
985 SearchEngine
::defaultNamespaces()
989 'message' => 'searchprofile-images',
990 'tooltip' => 'searchprofile-images-tooltip',
991 'namespaces' => array( NS_FILE
),
994 'message' => 'searchprofile-project',
995 'tooltip' => 'searchprofile-project-tooltip',
996 'namespaces' => SearchEngine
::helpNamespaces(),
997 'namespace-messages' => SearchEngine
::namespacesAsText(
998 SearchEngine
::helpNamespaces()
1002 'message' => 'searchprofile-everything',
1003 'tooltip' => 'searchprofile-everything-tooltip',
1004 'namespaces' => $nsAllSet,
1006 'advanced' => array(
1007 'message' => 'searchprofile-advanced',
1008 'tooltip' => 'searchprofile-advanced-tooltip',
1009 'namespaces' => self
::NAMESPACES_CURRENT
,
1013 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1015 foreach ( $profiles as &$data ) {
1016 if ( !is_array( $data['namespaces'] ) ) {
1019 sort( $data['namespaces'] );
1027 * @param $resultsShown
1031 protected function formHeader( $term, $resultsShown, $totalNum ) {
1032 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1035 if ( $this->startsWithImage( $term ) ) {
1037 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1040 $profiles = $this->getSearchProfiles();
1041 $lang = $this->getLanguage();
1043 // Outputs XML for Search Types
1044 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1045 $out .= Xml
::openElement( 'ul' );
1046 foreach ( $profiles as $id => $profile ) {
1047 if ( !isset( $profile['parameters'] ) ) {
1048 $profile['parameters'] = array();
1050 $profile['parameters']['profile'] = $id;
1052 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1053 $lang->commaList( $profile['namespace-messages'] ) : null;
1057 'class' => $this->profile
=== $id ?
'current' : 'normal'
1059 $this->makeSearchLink(
1062 $this->msg( $profile['message'] )->text(),
1063 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1064 $profile['parameters']
1068 $out .= Xml
::closeElement( 'ul' );
1069 $out .= Xml
::closeElement( 'div' );
1072 if ( $resultsShown > 0 ) {
1073 if ( $totalNum > 0 ) {
1074 $top = $this->msg( 'showingresultsheader' )
1075 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1076 ->params( wfEscapeWikiText( $term ) )
1077 ->numParams( $resultsShown )
1079 } elseif ( $resultsShown >= $this->limit
) {
1080 $top = $this->msg( 'showingresults' )
1081 ->numParams( $this->limit
, $this->offset +
1 )
1084 $top = $this->msg( 'showingresultsnum' )
1085 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1088 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1089 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1093 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1094 $out .= Xml
::closeElement( 'div' );
1100 * @param $term string
1103 protected function shortDialog( $term ) {
1104 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1105 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1107 $out .= Html
::input( 'search', $term, 'search', array(
1108 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1111 'class' => 'mw-ui-input',
1113 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1114 $out .= Xml
::submitButton(
1115 $this->msg( 'searchbutton' )->text(),
1116 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1118 return $out . $this->didYouMeanHtml
;
1122 * Make a search link with some target namespaces
1124 * @param $term String
1125 * @param array $namespaces ignored
1126 * @param string $label link's text
1127 * @param string $tooltip link's tooltip
1128 * @param array $params query string parameters
1129 * @return String: HTML fragment
1131 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1133 foreach ( $namespaces as $n ) {
1134 $opt['ns' . $n] = 1;
1136 $opt['redirs'] = $this->searchRedirects
;
1138 $stParams = array_merge(
1141 'fulltext' => $this->msg( 'search' )->text()
1146 return Xml
::element(
1149 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1157 * Check if query starts with image: prefix
1159 * @param string $term the string to check
1162 protected function startsWithImage( $term ) {
1165 $p = explode( ':', $term );
1166 if ( count( $p ) > 1 ) {
1167 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1173 * Check if query starts with all: prefix
1175 * @param string $term the string to check
1178 protected function startsWithAll( $term ) {
1180 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1182 $p = explode( ':', $term );
1183 if ( count( $p ) > 1 ) {
1184 return $p[0] == $allkeyword;
1192 * @return SearchEngine
1194 public function getSearchEngine() {
1195 if ( $this->searchEngine
=== null ) {
1196 $this->searchEngine
= $this->searchEngineType ?
1197 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1199 return $this->searchEngine
;
1203 * Current search profile.
1204 * @return null|string
1206 function getProfile() {
1207 return $this->profile
;
1211 * Current namespaces.
1214 function getNamespaces() {
1215 return $this->namespaces
;
1219 * Users of hook SpecialSearchSetupEngine can use this to
1220 * add more params to links to not lose selection when
1221 * user navigates search results.
1227 public function setExtraParam( $key, $value ) {
1228 $this->extraParams
[$key] = $value;
1231 protected function getGroupName() {