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, 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;
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',
89 // Strip underscores from title parameter; most of the time we'll want
90 // text form here. But don't strip underscores from actual text params!
91 $titleParam = str_replace( '_', ' ', $par );
93 $request = $this->getRequest();
95 // Fetch the search term
96 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
100 $this->saveNamespaces();
101 // Remove the token from the URL to prevent the user from inadvertently
102 // exposing it (e.g. by pasting it into a public wiki page) or undoing
103 // later settings changes (e.g. by reloading the page).
104 $query = $request->getValues();
105 unset( $query['title'], $query['nsRemember'] );
106 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
110 $this->searchEngineType
= $request->getVal( 'srbackend' );
112 if ( $request->getVal( 'fulltext' )
113 ||
!is_null( $request->getVal( 'offset' ) )
115 $this->showResults( $search );
117 $this->goResult( $search );
122 * Set up basic search parameters from the request and user settings.
124 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
126 public function load() {
127 $request = $this->getRequest();
128 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
129 $this->mPrefix
= $request->getVal( 'prefix', '' );
131 $user = $this->getUser();
133 # Extract manually requested namespaces
134 $nslist = $this->powerSearch( $request );
135 if ( !count( $nslist ) ) {
136 # Fallback to user preference
137 $nslist = SearchEngine
::userNamespaces( $user );
141 if ( !count( $nslist ) ) {
142 $profile = 'default';
145 $profile = $request->getVal( 'profile', $profile );
146 $profiles = $this->getSearchProfiles();
147 if ( $profile === null ) {
148 // BC with old request format
149 $profile = 'advanced';
150 foreach ( $profiles as $key => $data ) {
151 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
155 $this->namespaces
= $nslist;
156 } elseif ( $profile === 'advanced' ) {
157 $this->namespaces
= $nslist;
159 if ( isset( $profiles[$profile]['namespaces'] ) ) {
160 $this->namespaces
= $profiles[$profile]['namespaces'];
162 // Unknown profile requested
163 $profile = 'default';
164 $this->namespaces
= $profiles['default']['namespaces'];
168 $this->fulltext
= $request->getVal( 'fulltext' );
169 $this->profile
= $profile;
173 * If an exact title match can be found, jump straight ahead to it.
175 * @param string $term
177 public function goResult( $term ) {
178 $this->setupPage( $term );
179 # Try to go to page as entered.
180 $title = Title
::newFromText( $term );
181 # If the string cannot be used to create a title
182 if ( is_null( $title ) ) {
183 $this->showResults( $term );
187 # If there's an exact or very near match, jump right there.
188 $title = SearchEngine
::getNearMatch( $term );
190 if ( !is_null( $title ) ) {
191 $this->getOutput()->redirect( $title->getFullURL() );
195 # No match, generate an edit URL
196 $title = Title
::newFromText( $term );
197 if ( !is_null( $title ) ) {
198 Hooks
::run( 'SpecialSearchNogomatch', array( &$title ) );
200 $this->showResults( $term );
204 * @param string $term
206 public function showResults( $term ) {
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 );
214 $didYouMeanHtml = '';
216 Hooks
::run( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
218 $this->setupPage( $term );
220 $out = $this->getOutput();
222 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
223 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
224 if ( $searchFowardUrl ) {
225 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
226 $out->redirect( $url );
229 Xml
::openElement( 'fieldset' ) .
230 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
233 array( 'class' => 'mw-searchdisabled' ),
234 $this->msg( 'searchdisabled' )->text()
236 $this->msg( 'googlesearch' )->rawParams(
237 htmlspecialchars( $term ),
239 $this->msg( 'searchbutton' )->escaped()
241 Xml
::closeElement( 'fieldset' )
248 $title = Title
::newFromText( $term );
249 $showSuggestion = $title === null ||
!$title->isKnown();
250 $search->setShowSuggestion( $showSuggestion );
252 // fetch search results
253 $rewritten = $search->replacePrefixes( $term );
255 $titleMatches = $search->searchTitle( $rewritten );
256 $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 # html of did you mean... search suggestion link
293 Xml
::openElement( 'div', array( 'class' => 'searchdidyoumean' ) ) .
294 $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() .
295 Xml
::closeElement( 'div' );
298 if ( !Hooks
::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
299 # Hook requested termination
303 // start rendering the page
308 'id' => ( $this->isPowerSearch() ?
'powersearch' : 'search' ),
310 'action' => wfScript(),
315 // Get number of results
316 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
317 if ( $titleMatches ) {
318 $titleMatchesNum = $titleMatches->numRows();
319 $numTitleMatches = $titleMatches->getTotalHits();
321 if ( $textMatches ) {
322 $textMatchesNum = $textMatches->numRows();
323 $numTextMatches = $textMatches->getTotalHits();
325 $num = $titleMatchesNum +
$textMatchesNum;
326 $totalRes = $numTitleMatches +
$numTextMatches;
329 # This is an awful awful ID name. It's not a table, but we
330 # named it poorly from when this was a table so now we're
332 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
333 $this->shortDialog( $term, $num, $totalRes ) .
334 Xml
::closeElement( 'div' ) .
335 $this->searchProfileTabs( $term ) .
336 $this->searchOptions( $term ) .
337 Xml
::closeElement( 'form' ) .
341 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
342 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
343 // Empty query -- straight view of search form
347 $out->addHtml( "<div class='searchresults'>" );
351 if ( $num ||
$this->offset
) {
352 // Show the create link ahead
353 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
354 if ( $totalRes > $this->limit ||
$this->offset
) {
355 if ( $this->searchEngineType
!== null ) {
356 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
358 $prevnext = $this->getLanguage()->viewPrevNext(
359 $this->getPageTitle(),
362 $this->powerSearchOptions() +
array( 'search' => $term ),
363 $this->limit +
$this->offset
>= $totalRes
367 Hooks
::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
369 $out->parserOptions()->setEditSection( false );
370 if ( $titleMatches ) {
371 if ( $numTitleMatches > 0 ) {
372 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
373 $out->addHTML( $this->showMatches( $titleMatches ) );
375 $titleMatches->free();
377 if ( $textMatches && !$textStatus ) {
378 // output appropriate heading
379 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
380 // if no title matches the heading is redundant
381 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
384 // show interwiki results if any
385 if ( $textMatches->hasInterwikiResults() ) {
386 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
389 if ( $numTextMatches > 0 ) {
390 $out->addHTML( $this->showMatches( $textMatches ) );
393 $textMatches->free();
397 $out->addHTML( '<div class="error">' .
398 $textStatus->getMessage( 'search-error' ) . '</div>' );
400 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
401 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
402 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
405 $out->addHtml( "</div>" );
408 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
413 * @param Title $title
414 * @param int $num The number of search results found
415 * @param null|SearchResultSet $titleMatches Results from title search
416 * @param null|SearchResultSet $textMatches Results from text search
418 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
419 // show direct page/create link if applicable
421 // Check DBkey !== '' in case of fragment link only.
422 if ( is_null( $title ) ||
$title->getDBkey() === ''
423 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
424 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
427 // preserve the paragraph for margins etc...
428 $this->getOutput()->addHtml( '<p></p>' );
433 $messageName = 'searchmenu-new-nocreate';
434 $linkClass = 'mw-search-createlink';
436 if ( !$title->isExternal() ) {
437 if ( $title->isKnown() ) {
438 $messageName = 'searchmenu-exists';
439 $linkClass = 'mw-search-exists';
440 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
441 $messageName = 'searchmenu-new';
447 wfEscapeWikiText( $title->getPrefixedText() ),
448 Message
::numParam( $num )
450 Hooks
::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
452 // Extensions using the hook might still return an empty $messageName
453 if ( $messageName ) {
454 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
456 // preserve the paragraph for margins etc...
457 $this->getOutput()->addHtml( '<p></p>' );
462 * @param string $term
464 protected function setupPage( $term ) {
465 $out = $this->getOutput();
466 if ( strval( $term ) !== '' ) {
467 $out->setPageTitle( $this->msg( 'searchresults' ) );
468 $out->setHTMLTitle( $this->msg( 'pagetitle' )
469 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
470 ->inContentLanguage()->text()
473 // add javascript specific to special:search
474 $out->addModules( 'mediawiki.special.search' );
478 * Return true if current search is a power (advanced) search
482 protected function isPowerSearch() {
483 return $this->profile
=== 'advanced';
487 * Extract "power search" namespace settings from the request object,
488 * returning a list of index numbers to search.
490 * @param WebRequest $request
493 protected function powerSearch( &$request ) {
495 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
496 if ( $request->getCheck( 'ns' . $ns ) ) {
505 * Reconstruct the 'power search' options for links
509 protected function powerSearchOptions() {
511 if ( !$this->isPowerSearch() ) {
512 $opt['profile'] = $this->profile
;
514 foreach ( $this->namespaces
as $n ) {
519 return $opt +
$this->extraParams
;
523 * Save namespace preferences when we're supposed to
525 * @return bool Whether we wrote something
527 protected function saveNamespaces() {
528 $user = $this->getUser();
529 $request = $this->getRequest();
531 if ( $user->isLoggedIn() &&
532 $user->matchEditToken(
533 $request->getVal( 'nsRemember' ),
538 // Reset namespace preferences: namespaces are not searched
539 // when they're not mentioned in the URL parameters.
540 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
541 $user->setOption( 'searchNs' . $n, false );
543 // The request parameters include all the namespaces to be searched.
544 // Even if they're the same as an existing profile, they're not eaten.
545 foreach ( $this->namespaces
as $n ) {
546 $user->setOption( 'searchNs' . $n, true );
549 $user->saveSettings();
557 * Show whole set of results
559 * @param SearchResultSet $matches
563 protected function showMatches( &$matches ) {
566 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
568 $out = "<ul class='mw-search-results'>\n";
569 $result = $matches->next();
571 $out .= $this->showHit( $result, $terms );
572 $result = $matches->next();
576 // convert the whole thing to desired language variant
577 $out = $wgContLang->convert( $out );
583 * Format a single hit result
585 * @param SearchResult $result
586 * @param array $terms Terms to highlight
590 protected function showHit( $result, $terms ) {
592 if ( $result->isBrokenTitle() ) {
596 $title = $result->getTitle();
598 $titleSnippet = $result->getTitleSnippet();
600 if ( $titleSnippet == '' ) {
601 $titleSnippet = null;
604 $link_t = clone $title;
606 Hooks
::run( 'ShowSearchHitTitle',
607 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
609 $link = Linker
::linkKnown(
614 //If page content is not readable, just return the title.
615 //This is not quite safe, but better than showing excerpts from non-readable pages
616 //Note that hiding the entry entirely would screw up paging.
617 if ( !$title->userCan( 'read', $this->getUser() ) ) {
618 return "<li>{$link}</li>\n";
621 // If the page doesn't *exist*... our search index is out of date.
622 // The least confusing at this point is to drop the result.
623 // You may get less results, but... oh well. :P
624 if ( $result->isMissingRevision() ) {
628 // format redirects / relevant sections
629 $redirectTitle = $result->getRedirectTitle();
630 $redirectText = $result->getRedirectSnippet();
631 $sectionTitle = $result->getSectionTitle();
632 $sectionText = $result->getSectionSnippet();
633 $categorySnippet = $result->getCategorySnippet();
636 if ( !is_null( $redirectTitle ) ) {
637 if ( $redirectText == '' ) {
638 $redirectText = null;
641 $redirect = "<span class='searchalttitle'>" .
642 $this->msg( 'search-redirect' )->rawParams(
643 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
648 if ( !is_null( $sectionTitle ) ) {
649 if ( $sectionText == '' ) {
653 $section = "<span class='searchalttitle'>" .
654 $this->msg( 'search-section' )->rawParams(
655 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
660 if ( $categorySnippet ) {
661 $category = "<span class='searchalttitle'>" .
662 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
666 // format text extract
667 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
669 $lang = $this->getLanguage();
671 // format description
672 $byteSize = $result->getByteSize();
673 $wordCount = $result->getWordCount();
674 $timestamp = $result->getTimestamp();
675 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
676 ->numParams( $wordCount )->escaped();
678 if ( $title->getNamespace() == NS_CATEGORY
) {
679 $cat = Category
::newFromTitle( $title );
680 $size = $this->msg( 'search-result-category-size' )
681 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
685 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
688 // Include a thumbnail for media files...
689 if ( $title->getNamespace() == NS_FILE
) {
690 $img = $result->getFile();
691 $img = $img ?
: wfFindFile( $title );
692 if ( $result->isFileMatch() ) {
693 $fileMatch = "<span class='searchalttitle'>" .
694 $this->msg( 'search-file-match' )->escaped() . "</span>";
697 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
699 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
700 // Float doesn't seem to interact well with the bullets.
701 // Table messes up vertical alignment of the bullets.
702 // Bullets are therefore disabled (didn't look great anyway).
704 '<table class="searchResultImage">' .
706 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
707 $thumb->toHtml( array( 'desc-link' => true ) ) .
709 '<td style="vertical-align: top;">' .
710 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
712 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
724 if ( Hooks
::run( 'ShowSearchHit', array(
725 $this, $result, $terms,
726 &$link, &$redirect, &$section, &$extract,
727 &$score, &$size, &$date, &$related,
730 $html = "<li><div class='mw-search-result-heading'>" .
731 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
732 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
740 * Show results from other wikis
742 * @param SearchResultSet|array $matches
743 * @param string $query
747 protected function showInterwiki( $matches, $query ) {
750 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
751 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
752 $out .= "<ul class='mw-search-iwresults'>\n";
754 // work out custom project captions
755 $customCaptions = array();
756 // format per line <iwprefix>:<caption>
757 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
758 foreach ( $customLines as $line ) {
759 $parts = explode( ":", $line, 2 );
760 if ( count( $parts ) == 2 ) { // validate line
761 $customCaptions[$parts[0]] = $parts[1];
765 if ( !is_array( $matches ) ) {
766 $matches = array( $matches );
769 foreach ( $matches as $set ) {
771 $result = $set->next();
773 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
774 $prev = $result->getInterwikiPrefix();
775 $result = $set->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 );
789 * Show single interwiki link
791 * @param SearchResult $result
792 * @param string $lastInterwiki
793 * @param string $query
794 * @param array $customCaptions Interwiki prefix -> caption
798 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
800 if ( $result->isBrokenTitle() ) {
804 $title = $result->getTitle();
806 $titleSnippet = $result->getTitleSnippet();
808 if ( $titleSnippet == '' ) {
809 $titleSnippet = null;
812 $link = Linker
::linkKnown(
817 // format redirect if any
818 $redirectTitle = $result->getRedirectTitle();
819 $redirectText = $result->getRedirectSnippet();
821 if ( !is_null( $redirectTitle ) ) {
822 if ( $redirectText == '' ) {
823 $redirectText = null;
826 $redirect = "<span class='searchalttitle'>" .
827 $this->msg( 'search-redirect' )->rawParams(
828 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
833 // display project name
834 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
835 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
836 // captions from 'search-interwiki-custom'
837 $caption = $customCaptions[$title->getInterwiki()];
839 // default is to show the hostname of the other wiki which might suck
840 // if there are many wikis on one hostname
841 $parsed = wfParseUrl( $title->getFullURL() );
842 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
844 // "more results" link (special page stuff could be localized, but we might not know target lang)
845 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
846 $searchLink = Linker
::linkKnown(
848 $this->msg( 'search-interwiki-more' )->text(),
852 'fulltext' => 'Search'
855 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
856 {$searchLink}</span>{$caption}</div>\n<ul>";
859 $out .= "<li>{$link} {$redirect}</li>\n";
865 * Generates the power search box at [[Special:Search]]
867 * @param string $term Search term
869 * @return string HTML form
871 protected function powerSearchBox( $term, $opts ) {
874 // Groups namespaces into rows according to subject
876 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
877 $subject = MWNamespace
::getSubject( $namespace );
878 if ( !array_key_exists( $subject, $rows ) ) {
879 $rows[$subject] = "";
882 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
884 $name = $this->msg( 'blanknamespace' )->text();
888 Xml
::openElement( 'td' ) .
892 "mw-search-ns{$namespace}",
893 in_array( $namespace, $this->namespaces
)
895 Xml
::closeElement( 'td' );
898 $rows = array_values( $rows );
899 $numRows = count( $rows );
901 // Lays out namespaces in multiple floating two-column tables so they'll
902 // be arranged nicely while still accommodating different screen widths
903 $namespaceTables = '';
904 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
905 $namespaceTables .= Xml
::openElement( 'table' );
907 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
908 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
911 $namespaceTables .= Xml
::closeElement( 'table' );
914 $showSections = array( 'namespaceTables' => $namespaceTables );
916 Hooks
::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
919 foreach ( $opts as $key => $value ) {
920 $hidden .= Html
::hidden( $key, $value );
923 # Stuff to feed saveNamespaces()
925 $user = $this->getUser();
926 if ( $user->isLoggedIn() ) {
927 $remember .= Xml
::checkLabel(
928 $this->msg( 'powersearch-remember' )->text(),
930 'mw-search-powersearch-remember',
932 // The token goes here rather than in a hidden field so it
933 // is only sent when necessary (not every form submission).
934 array( 'value' => $user->getEditToken(
941 // Return final output
942 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
943 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
944 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
945 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
946 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
947 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
949 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
951 Xml
::closeElement( 'fieldset' );
957 protected function getSearchProfiles() {
958 // Builds list of Search Types (profiles)
959 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
963 'message' => 'searchprofile-articles',
964 'tooltip' => 'searchprofile-articles-tooltip',
965 'namespaces' => SearchEngine
::defaultNamespaces(),
966 'namespace-messages' => SearchEngine
::namespacesAsText(
967 SearchEngine
::defaultNamespaces()
971 'message' => 'searchprofile-images',
972 'tooltip' => 'searchprofile-images-tooltip',
973 'namespaces' => array( NS_FILE
),
976 'message' => 'searchprofile-everything',
977 'tooltip' => 'searchprofile-everything-tooltip',
978 'namespaces' => $nsAllSet,
981 'message' => 'searchprofile-advanced',
982 'tooltip' => 'searchprofile-advanced-tooltip',
983 'namespaces' => self
::NAMESPACES_CURRENT
,
987 Hooks
::run( 'SpecialSearchProfiles', array( &$profiles ) );
989 foreach ( $profiles as &$data ) {
990 if ( !is_array( $data['namespaces'] ) ) {
993 sort( $data['namespaces'] );
1000 * @param string $term
1003 protected function searchProfileTabs( $term ) {
1004 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1007 if ( $this->startsWithImage( $term ) ) {
1009 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1012 $profiles = $this->getSearchProfiles();
1013 $lang = $this->getLanguage();
1015 // Outputs XML for Search Types
1016 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1017 $out .= Xml
::openElement( 'ul' );
1018 foreach ( $profiles as $id => $profile ) {
1019 if ( !isset( $profile['parameters'] ) ) {
1020 $profile['parameters'] = array();
1022 $profile['parameters']['profile'] = $id;
1024 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1025 $lang->commaList( $profile['namespace-messages'] ) : null;
1029 'class' => $this->profile
=== $id ?
'current' : 'normal'
1031 $this->makeSearchLink(
1034 $this->msg( $profile['message'] )->text(),
1035 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1036 $profile['parameters']
1040 $out .= Xml
::closeElement( 'ul' );
1041 $out .= Xml
::closeElement( 'div' );
1042 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1043 $out .= Xml
::closeElement( 'div' );
1049 * @param string $term Search term
1052 protected function searchOptions( $term ) {
1055 $opts['profile'] = $this->profile
;
1057 if ( $this->isPowerSearch() ) {
1058 $out .= $this->powerSearchBox( $term, $opts );
1061 Hooks
::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1069 * @param string $term
1070 * @param int $resultsShown
1071 * @param int $totalNum
1074 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1075 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1076 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1078 $out .= Html
::input( 'search', $term, 'search', array(
1079 'id' => $this->isPowerSearch() ?
'powerSearchText' : 'searchText',
1081 'autofocus' => trim( $term ) === '',
1082 'class' => 'mw-ui-input mw-ui-input-inline',
1084 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1085 $out .= Html
::submitButton(
1086 $this->msg( 'searchbutton' )->text(),
1087 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1088 array( 'mw-ui-progressive' )
1092 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1093 $top = $this->msg( 'search-showingresults' )
1094 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1095 ->numParams( $resultsShown )
1097 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1098 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1105 * Make a search link with some target namespaces
1107 * @param string $term
1108 * @param array $namespaces Ignored
1109 * @param string $label Link's text
1110 * @param string $tooltip Link's tooltip
1111 * @param array $params Query string parameters
1112 * @return string HTML fragment
1114 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1116 foreach ( $namespaces as $n ) {
1117 $opt['ns' . $n] = 1;
1120 $stParams = array_merge(
1123 'fulltext' => $this->msg( 'search' )->text()
1128 return Xml
::element(
1131 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1139 * Check if query starts with image: prefix
1141 * @param string $term The string to check
1144 protected function startsWithImage( $term ) {
1147 $parts = explode( ':', $term );
1148 if ( count( $parts ) > 1 ) {
1149 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1156 * Check if query starts with all: prefix
1158 * @param string $term The string to check
1161 protected function startsWithAll( $term ) {
1163 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1165 $parts = explode( ':', $term );
1166 if ( count( $parts ) > 1 ) {
1167 return $parts[0] == $allkeyword;
1176 * @return SearchEngine
1178 public function getSearchEngine() {
1179 if ( $this->searchEngine
=== null ) {
1180 $this->searchEngine
= $this->searchEngineType ?
1181 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1184 return $this->searchEngine
;
1188 * Current search profile.
1189 * @return null|string
1191 function getProfile() {
1192 return $this->profile
;
1196 * Current namespaces.
1199 function getNamespaces() {
1200 return $this->namespaces
;
1204 * Users of hook SpecialSearchSetupEngine can use this to
1205 * add more params to links to not lose selection when
1206 * user navigates search results.
1209 * @param string $key
1210 * @param mixed $value
1212 public function setExtraParam( $key, $value ) {
1213 $this->extraParams
[$key] = $value;
1216 protected function getGroupName() {