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.
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
47 /** @var array For links */
48 protected $extraParams = array();
50 /** @var string No idea, apparently used by some other classes */
56 protected $limit, $offset;
61 protected $namespaces;
66 protected $didYouMeanHtml, $fulltext;
68 const NAMESPACES_CURRENT
= 'sense';
70 public function __construct() {
71 parent
::__construct( 'Search' );
79 public function execute( $par ) {
81 $this->outputHeader();
82 $out = $this->getOutput();
83 $out->allowClickjacking();
84 $out->addModuleStyles( array(
85 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button'
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
92 $request = $this->getRequest();
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 $this->searchEngineType
= $request->getVal( 'srbackend' );
101 if ( $request->getVal( 'fulltext' )
102 ||
!is_null( $request->getVal( 'offset' ) )
104 $this->showResults( $search );
106 $this->goResult( $search );
111 * Set up basic search parameters from the request and user settings.
113 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
115 public function load() {
116 $request = $this->getRequest();
117 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20 );
118 $this->mPrefix
= $request->getVal( 'prefix', '' );
120 $user = $this->getUser();
122 # Extract manually requested namespaces
123 $nslist = $this->powerSearch( $request );
124 if ( !count( $nslist ) ) {
125 # Fallback to user preference
126 $nslist = SearchEngine
::userNamespaces( $user );
130 if ( !count( $nslist ) ) {
131 $profile = 'default';
134 $profile = $request->getVal( 'profile', $profile );
135 $profiles = $this->getSearchProfiles();
136 if ( $profile === null ) {
137 // BC with old request format
138 $profile = 'advanced';
139 foreach ( $profiles as $key => $data ) {
140 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
144 $this->namespaces
= $nslist;
145 } elseif ( $profile === 'advanced' ) {
146 $this->namespaces
= $nslist;
148 if ( isset( $profiles[$profile]['namespaces'] ) ) {
149 $this->namespaces
= $profiles[$profile]['namespaces'];
151 // Unknown profile requested
152 $profile = 'default';
153 $this->namespaces
= $profiles['default']['namespaces'];
157 $this->didYouMeanHtml
= ''; # html of did you mean... link
158 $this->fulltext
= $request->getVal( 'fulltext' );
159 $this->profile
= $profile;
163 * If an exact title match can be found, jump straight ahead to it.
165 * @param string $term
167 public function goResult( $term ) {
168 $this->setupPage( $term );
169 # Try to go to page as entered.
170 $title = Title
::newFromText( $term );
171 # If the string cannot be used to create a title
172 if ( is_null( $title ) ) {
173 $this->showResults( $term );
177 # If there's an exact or very near match, jump right there.
178 $title = SearchEngine
::getNearMatch( $term );
180 if ( !is_null( $title ) ) {
181 $this->getOutput()->redirect( $title->getFullURL() );
185 # No match, generate an edit URL
186 $title = Title
::newFromText( $term );
187 if ( !is_null( $title ) ) {
189 wfRunHooks( 'SpecialSearchNogomatch', array( &$title ) );
190 wfDebugLog( 'nogomatch', $title->getFullText(), 'private' );
192 # If the feature is enabled, go straight to the edit page
194 $this->getOutput()->redirect( $title->getFullURL( array( 'action' => 'edit' ) ) );
199 $this->showResults( $term );
203 * @param string $term
205 public function showResults( $term ) {
206 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
208 $profile = new ProfileSection( __METHOD__
);
209 $search = $this->getSearchEngine();
210 $search->setLimitOffset( $this->limit
, $this->offset
);
211 $search->setNamespaces( $this->namespaces
);
212 $search->prefix
= $this->mPrefix
;
213 $term = $search->transformSearchTerm( $term );
215 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
217 $this->setupPage( $term );
219 $out = $this->getOutput();
221 if ( $wgDisableTextSearch ) {
222 if ( $wgSearchForwardUrl ) {
223 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
224 $out->redirect( $url );
227 Xml
::openElement( 'fieldset' ) .
228 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
231 array( 'class' => 'mw-searchdisabled' ),
232 $this->msg( 'searchdisabled' )->text()
234 $this->msg( 'googlesearch' )->rawParams(
235 htmlspecialchars( $term ),
237 $this->msg( 'searchbutton' )->escaped()
239 Xml
::closeElement( 'fieldset' )
246 $title = Title
::newFromText( $term );
247 $showSuggestion = $title === null ||
!$title->isKnown();
248 $search->setShowSuggestion( $showSuggestion );
250 // fetch search results
251 $rewritten = $search->replacePrefixes( $term );
253 $titleMatches = $search->searchTitle( $rewritten );
254 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
255 $textMatches = $search->searchText( $rewritten );
259 if ( $textMatches instanceof Status
) {
260 $textStatus = $textMatches;
264 // did you mean... suggestions
265 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
266 # mirror Go/Search behavior of original request ..
267 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
269 if ( $this->fulltext
!= null ) {
270 $didYouMeanParams['fulltext'] = $this->fulltext
;
273 $stParams = array_merge(
275 $this->powerSearchOptions()
278 $suggestionSnippet = $textMatches->getSuggestionSnippet();
280 if ( $suggestionSnippet == '' ) {
281 $suggestionSnippet = null;
284 $suggestLink = Linker
::linkKnown(
285 $this->getPageTitle(),
291 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
292 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
295 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
296 # Hook requested termination
300 // start rendering the page
305 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
307 'action' => $wgScript
312 # This is an awful awful ID name. It's not a table, but we
313 # named it poorly from when this was a table so now we're
315 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
316 $this->shortDialog( $term ) .
317 Xml
::closeElement( 'div' )
320 // Sometimes the search engine knows there are too many hits
321 if ( $titleMatches instanceof SearchResultTooMany
) {
322 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
327 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
328 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
329 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
330 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
331 $out->addHTML( '</form>' );
333 // Empty query -- straight view of search form
337 // Get number of results
338 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
339 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
340 // Total initial query matches (possible false positives)
341 $num = $titleMatchesNum +
$textMatchesNum;
343 // Get total actual results (after second filtering, if any)
344 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
345 $titleMatches->getTotalHits() : $titleMatchesNum;
346 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
347 $textMatches->getTotalHits() : $textMatchesNum;
349 // get total number of results if backend can calculate it
351 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
352 $totalRes +
= $titleMatches->getTotalHits();
354 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
355 $totalRes +
= $textMatches->getTotalHits();
358 // show number of results and current offset
359 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
360 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
362 $out->addHtml( Xml
::closeElement( 'form' ) );
363 $out->addHtml( "<div class='searchresults'>" );
367 if ( $num ||
$this->offset
) {
368 // Show the create link ahead
369 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
370 if ( $totalRes > $this->limit ||
$this->offset
) {
371 $prevnext = $this->getLanguage()->viewPrevNext(
372 $this->getPageTitle(),
375 $this->powerSearchOptions() +
array( 'search' => $term ),
376 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
379 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
381 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
384 $out->parserOptions()->setEditSection( false );
385 if ( $titleMatches ) {
386 if ( $numTitleMatches > 0 ) {
387 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
388 $out->addHTML( $this->showMatches( $titleMatches ) );
390 $titleMatches->free();
392 if ( $textMatches && !$textStatus ) {
393 // output appropriate heading
394 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
395 // if no title matches the heading is redundant
396 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
399 // show interwiki results if any
400 if ( $textMatches->hasInterwikiResults() ) {
401 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
404 if ( $numTextMatches > 0 ) {
405 $out->addHTML( $this->showMatches( $textMatches ) );
408 $textMatches->free();
412 $out->addHTML( '<div class="error">' .
413 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
415 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
416 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
417 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
420 $out->addHtml( "</div>" );
423 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
428 * @param Title $title
429 * @param int $num The number of search results found
430 * @param null|SearchResultSet $titleMatches Results from title search
431 * @param null|SearchResultSet $textMatches Results from text search
433 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
434 // show direct page/create link if applicable
436 // Check DBkey !== '' in case of fragment link only.
437 if ( is_null( $title ) ||
$title->getDBkey() === ''
438 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
439 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
442 // preserve the paragraph for margins etc...
443 $this->getOutput()->addHtml( '<p></p>' );
448 if ( $title->isKnown() ) {
449 $messageName = 'searchmenu-exists';
450 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
451 $messageName = 'searchmenu-new';
453 $messageName = 'searchmenu-new-nocreate';
457 wfEscapeWikiText( $title->getPrefixedText() ),
458 Message
::numParam( $num )
460 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
462 // Extensions using the hook might still return an empty $messageName
463 if ( $messageName ) {
464 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
466 // preserve the paragraph for margins etc...
467 $this->getOutput()->addHtml( '<p></p>' );
472 * @param string $term
474 protected function setupPage( $term ) {
475 # Should advanced UI be used?
476 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
477 $out = $this->getOutput();
478 if ( strval( $term ) !== '' ) {
479 $out->setPageTitle( $this->msg( 'searchresults' ) );
480 $out->setHTMLTitle( $this->msg( 'pagetitle' )
481 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
482 ->inContentLanguage()->text()
485 // add javascript specific to special:search
486 $out->addModules( 'mediawiki.special.search' );
490 * Extract "power search" namespace settings from the request object,
491 * returning a list of index numbers to search.
493 * @param WebRequest $request
496 protected function powerSearch( &$request ) {
498 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
499 if ( $request->getCheck( 'ns' . $ns ) ) {
508 * Reconstruct the 'power search' options for links
512 protected function powerSearchOptions() {
514 if ( $this->profile
!== 'advanced' ) {
515 $opt['profile'] = $this->profile
;
517 foreach ( $this->namespaces
as $n ) {
522 return $opt +
$this->extraParams
;
526 * Show whole set of results
528 * @param SearchResultSet $matches
532 protected function showMatches( &$matches ) {
535 $profile = new ProfileSection( __METHOD__
);
536 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
538 $out = "<ul class='mw-search-results'>\n";
539 $result = $matches->next();
541 $out .= $this->showHit( $result, $terms );
542 $result = $matches->next();
546 // convert the whole thing to desired language variant
547 $out = $wgContLang->convert( $out );
553 * Format a single hit result
555 * @param SearchResult $result
556 * @param array $terms Terms to highlight
560 protected function showHit( $result, $terms ) {
561 $profile = new ProfileSection( __METHOD__
);
563 if ( $result->isBrokenTitle() ) {
567 $title = $result->getTitle();
569 $titleSnippet = $result->getTitleSnippet( $terms );
571 if ( $titleSnippet == '' ) {
572 $titleSnippet = null;
575 $link_t = clone $title;
577 wfRunHooks( 'ShowSearchHitTitle',
578 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
580 $link = Linker
::linkKnown(
585 //If page content is not readable, just return the title.
586 //This is not quite safe, but better than showing excerpts from non-readable pages
587 //Note that hiding the entry entirely would screw up paging.
588 if ( !$title->userCan( 'read', $this->getUser() ) ) {
589 return "<li>{$link}</li>\n";
592 // If the page doesn't *exist*... our search index is out of date.
593 // The least confusing at this point is to drop the result.
594 // You may get less results, but... oh well. :P
595 if ( $result->isMissingRevision() ) {
599 // format redirects / relevant sections
600 $redirectTitle = $result->getRedirectTitle();
601 $redirectText = $result->getRedirectSnippet( $terms );
602 $sectionTitle = $result->getSectionTitle();
603 $sectionText = $result->getSectionSnippet( $terms );
606 if ( !is_null( $redirectTitle ) ) {
607 if ( $redirectText == '' ) {
608 $redirectText = null;
611 $redirect = "<span class='searchalttitle'>" .
612 $this->msg( 'search-redirect' )->rawParams(
613 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
619 if ( !is_null( $sectionTitle ) ) {
620 if ( $sectionText == '' ) {
624 $section = "<span class='searchalttitle'>" .
625 $this->msg( 'search-section' )->rawParams(
626 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
630 // format text extract
631 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
633 $lang = $this->getLanguage();
636 if ( is_null( $result->getScore() ) ) {
637 // Search engine doesn't report scoring info
640 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
641 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
645 // format description
646 $byteSize = $result->getByteSize();
647 $wordCount = $result->getWordCount();
648 $timestamp = $result->getTimestamp();
649 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
650 ->numParams( $wordCount )->escaped();
652 if ( $title->getNamespace() == NS_CATEGORY
) {
653 $cat = Category
::newFromTitle( $title );
654 $size = $this->msg( 'search-result-category-size' )
655 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
659 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
661 // link to related articles if supported
663 if ( $result->hasRelated() ) {
664 $stParams = array_merge(
665 $this->powerSearchOptions(),
667 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
668 ':' . $title->getPrefixedText(),
669 'fulltext' => $this->msg( 'search' )->text()
673 $related = ' -- ' . Linker
::linkKnown(
674 $this->getPageTitle(),
675 $this->msg( 'search-relatedarticle' )->text(),
682 // Include a thumbnail for media files...
683 if ( $title->getNamespace() == NS_FILE
) {
684 $img = $result->getFile();
685 $img = $img ?
: wfFindFile( $title );
686 if ( $result->isFileMatch() ) {
687 $fileMatch = "<span class='searchalttitle'>" .
688 $this->msg( 'search-file-match' )->escaped() . "</span>";
691 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
693 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
694 // Float doesn't seem to interact well with the bullets.
695 // Table messes up vertical alignment of the bullets.
696 // Bullets are therefore disabled (didn't look great anyway).
698 '<table class="searchResultImage">' .
700 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
701 $thumb->toHtml( array( 'desc-link' => true ) ) .
703 '<td style="vertical-align: top;">' .
704 "{$link} {$fileMatch}" .
706 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
717 if ( wfRunHooks( 'ShowSearchHit', array(
718 $this, $result, $terms,
719 &$link, &$redirect, &$section, &$extract,
720 &$score, &$size, &$date, &$related,
723 $html = "<li><div class='mw-search-result-heading'>" .
724 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
725 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
733 * Show results from other wikis
735 * @param SearchResultSet|array $matches
736 * @param string $query
740 protected function showInterwiki( $matches, $query ) {
742 $profile = new ProfileSection( __METHOD__
);
744 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
745 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
746 $out .= "<ul class='mw-search-iwresults'>\n";
748 // work out custom project captions
749 $customCaptions = array();
750 // format per line <iwprefix>:<caption>
751 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
752 foreach ( $customLines as $line ) {
753 $parts = explode( ":", $line, 2 );
754 if ( count( $parts ) == 2 ) { // validate line
755 $customCaptions[$parts[0]] = $parts[1];
759 if ( !is_array( $matches ) ) {
760 $matches = array( $matches );
763 foreach ( $matches as $set ) {
765 $result = $set->next();
767 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
768 $prev = $result->getInterwikiPrefix();
769 $result = $set->next();
773 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
774 $out .= "</ul></div>\n";
776 // convert the whole thing to desired language variant
777 $out = $wgContLang->convert( $out );
783 * Show single interwiki link
785 * @param SearchResult $result
786 * @param string $lastInterwiki
787 * @param string $query
788 * @param array $customCaptions iw prefix -> caption
792 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
793 $profile = new ProfileSection( __METHOD__
);
795 if ( $result->isBrokenTitle() ) {
799 $title = $result->getTitle();
801 $titleSnippet = $result->getTitleSnippet();
803 if ( $titleSnippet == '' ) {
804 $titleSnippet = null;
807 $link = Linker
::linkKnown(
812 // format redirect if any
813 $redirectTitle = $result->getRedirectTitle();
814 $redirectText = $result->getRedirectSnippet();
816 if ( !is_null( $redirectTitle ) ) {
817 if ( $redirectText == '' ) {
818 $redirectText = null;
821 $redirect = "<span class='searchalttitle'>" .
822 $this->msg( 'search-redirect' )->rawParams(
823 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
828 // display project name
829 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
830 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
831 // captions from 'search-interwiki-custom'
832 $caption = $customCaptions[$title->getInterwiki()];
834 // default is to show the hostname of the other wiki which might suck
835 // if there are many wikis on one hostname
836 $parsed = wfParseUrl( $title->getFullURL() );
837 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
839 // "more results" link (special page stuff could be localized, but we might not know target lang)
840 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
841 $searchLink = Linker
::linkKnown(
843 $this->msg( 'search-interwiki-more' )->text(),
847 'fulltext' => 'Search'
850 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
851 {$searchLink}</span>{$caption}</div>\n<ul>";
854 $out .= "<li>{$link} {$redirect}</li>\n";
860 * @param string $profile
861 * @param string $term
864 protected function getProfileForm( $profile, $term ) {
867 $opts['profile'] = $this->profile
;
869 if ( $profile === 'advanced' ) {
870 return $this->powerSearchBox( $term, $opts );
873 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
880 * Generates the power search box at [[Special:Search]]
882 * @param string $term Search term
884 * @return string HTML form
886 protected function powerSearchBox( $term, $opts ) {
889 // Groups namespaces into rows according to subject
891 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
892 $subject = MWNamespace
::getSubject( $namespace );
893 if ( !array_key_exists( $subject, $rows ) ) {
894 $rows[$subject] = "";
897 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
899 $name = $this->msg( 'blanknamespace' )->text();
904 'td', array( 'style' => 'white-space: nowrap' )
909 "mw-search-ns{$namespace}",
910 in_array( $namespace, $this->namespaces
)
912 Xml
::closeElement( 'td' );
915 $rows = array_values( $rows );
916 $numRows = count( $rows );
918 // Lays out namespaces in multiple floating two-column tables so they'll
919 // be arranged nicely while still accommodating different screen widths
920 $namespaceTables = '';
921 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
922 $namespaceTables .= Xml
::openElement(
924 array( 'cellpadding' => 0, 'cellspacing' => 0 )
927 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
928 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
931 $namespaceTables .= Xml
::closeElement( 'table' );
934 $showSections = array( 'namespaceTables' => $namespaceTables );
936 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
939 foreach ( $opts as $key => $value ) {
940 $hidden .= Html
::hidden( $key, $value );
943 // Return final output
944 return Xml
::openElement(
946 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
948 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
949 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
950 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
951 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
952 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
954 Xml
::closeElement( 'fieldset' );
960 protected function getSearchProfiles() {
961 // Builds list of Search Types (profiles)
962 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
966 'message' => 'searchprofile-articles',
967 'tooltip' => 'searchprofile-articles-tooltip',
968 'namespaces' => SearchEngine
::defaultNamespaces(),
969 'namespace-messages' => SearchEngine
::namespacesAsText(
970 SearchEngine
::defaultNamespaces()
974 'message' => 'searchprofile-images',
975 'tooltip' => 'searchprofile-images-tooltip',
976 'namespaces' => array( NS_FILE
),
979 'message' => 'searchprofile-project',
980 'tooltip' => 'searchprofile-project-tooltip',
981 'namespaces' => SearchEngine
::helpNamespaces(),
982 'namespace-messages' => SearchEngine
::namespacesAsText(
983 SearchEngine
::helpNamespaces()
987 'message' => 'searchprofile-everything',
988 'tooltip' => 'searchprofile-everything-tooltip',
989 'namespaces' => $nsAllSet,
992 'message' => 'searchprofile-advanced',
993 'tooltip' => 'searchprofile-advanced-tooltip',
994 'namespaces' => self
::NAMESPACES_CURRENT
,
998 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1000 foreach ( $profiles as &$data ) {
1001 if ( !is_array( $data['namespaces'] ) ) {
1004 sort( $data['namespaces'] );
1011 * @param string $term
1012 * @param int $resultsShown
1013 * @param int $totalNum
1016 protected function formHeader( $term, $resultsShown, $totalNum ) {
1017 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1020 if ( $this->startsWithImage( $term ) ) {
1022 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1025 $profiles = $this->getSearchProfiles();
1026 $lang = $this->getLanguage();
1028 // Outputs XML for Search Types
1029 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1030 $out .= Xml
::openElement( 'ul' );
1031 foreach ( $profiles as $id => $profile ) {
1032 if ( !isset( $profile['parameters'] ) ) {
1033 $profile['parameters'] = array();
1035 $profile['parameters']['profile'] = $id;
1037 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1038 $lang->commaList( $profile['namespace-messages'] ) : null;
1042 'class' => $this->profile
=== $id ?
'current' : 'normal'
1044 $this->makeSearchLink(
1047 $this->msg( $profile['message'] )->text(),
1048 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1049 $profile['parameters']
1053 $out .= Xml
::closeElement( 'ul' );
1054 $out .= Xml
::closeElement( 'div' );
1057 if ( $resultsShown > 0 ) {
1058 if ( $totalNum > 0 ) {
1059 $top = $this->msg( 'showingresultsheader' )
1060 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1061 ->params( wfEscapeWikiText( $term ) )
1062 ->numParams( $resultsShown )
1064 } elseif ( $resultsShown >= $this->limit
) {
1065 $top = $this->msg( 'showingresults' )
1066 ->numParams( $this->limit
, $this->offset +
1 )
1069 $top = $this->msg( 'showingresultsnum' )
1070 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1073 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1074 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1078 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1079 $out .= Xml
::closeElement( 'div' );
1085 * @param string $term
1088 protected function shortDialog( $term ) {
1089 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1090 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1092 $out .= Html
::input( 'search', $term, 'search', array(
1093 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1096 'class' => 'mw-ui-input',
1098 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1099 $out .= Xml
::submitButton(
1100 $this->msg( 'searchbutton' )->text(),
1101 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1104 return $out . $this->didYouMeanHtml
;
1108 * Make a search link with some target namespaces
1110 * @param string $term
1111 * @param array $namespaces Ignored
1112 * @param string $label Link's text
1113 * @param string $tooltip Link's tooltip
1114 * @param array $params Query string parameters
1115 * @return string HTML fragment
1117 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1119 foreach ( $namespaces as $n ) {
1120 $opt['ns' . $n] = 1;
1123 $stParams = array_merge(
1126 'fulltext' => $this->msg( 'search' )->text()
1131 return Xml
::element(
1134 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1142 * Check if query starts with image: prefix
1144 * @param string $term The string to check
1147 protected function startsWithImage( $term ) {
1150 $parts = explode( ':', $term );
1151 if ( count( $parts ) > 1 ) {
1152 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1159 * Check if query starts with all: prefix
1161 * @param string $term The string to check
1164 protected function startsWithAll( $term ) {
1166 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1168 $parts = explode( ':', $term );
1169 if ( count( $parts ) > 1 ) {
1170 return $parts[0] == $allkeyword;
1179 * @return SearchEngine
1181 public function getSearchEngine() {
1182 if ( $this->searchEngine
=== null ) {
1183 $this->searchEngine
= $this->searchEngineType ?
1184 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.
1212 * @param string $key
1213 * @param mixed $value
1215 public function setExtraParam( $key, $value ) {
1216 $this->extraParams
[$key] = $value;
1219 protected function getGroupName() {