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;
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',
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->didYouMeanHtml
= ''; # html of did you mean... link
169 $this->fulltext
= $request->getVal( 'fulltext' );
170 $this->profile
= $profile;
174 * If an exact title match can be found, jump straight ahead to it.
176 * @param string $term
178 public function goResult( $term ) {
179 $this->setupPage( $term );
180 # Try to go to page as entered.
181 $title = Title
::newFromText( $term );
182 # If the string cannot be used to create a title
183 if ( is_null( $title ) ) {
184 $this->showResults( $term );
188 # If there's an exact or very near match, jump right there.
189 $title = SearchEngine
::getNearMatch( $term );
191 if ( !is_null( $title ) ) {
192 $this->getOutput()->redirect( $title->getFullURL() );
196 # No match, generate an edit URL
197 $title = Title
::newFromText( $term );
198 if ( !is_null( $title ) ) {
199 wfRunHooks( 'SpecialSearchNogomatch', array( &$title ) );
200 wfDebugLog( 'nogomatch', $title->getFullText(), 'private' );
202 # If the feature is enabled, go straight to the edit page
203 if ( $this->getConfig()->get( 'GoToEdit' ) ) {
204 $this->getOutput()->redirect( $title->getFullURL( array( 'action' => 'edit' ) ) );
209 $this->showResults( $term );
213 * @param string $term
215 public function showResults( $term ) {
218 $profile = new ProfileSection( __METHOD__
);
219 $search = $this->getSearchEngine();
220 $search->setLimitOffset( $this->limit
, $this->offset
);
221 $search->setNamespaces( $this->namespaces
);
222 $search->prefix
= $this->mPrefix
;
223 $term = $search->transformSearchTerm( $term );
225 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
227 $this->setupPage( $term );
229 $out = $this->getOutput();
231 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
232 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
233 if ( $searchFowardUrl ) {
234 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
235 $out->redirect( $url );
238 Xml
::openElement( 'fieldset' ) .
239 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
242 array( 'class' => 'mw-searchdisabled' ),
243 $this->msg( 'searchdisabled' )->text()
245 $this->msg( 'googlesearch' )->rawParams(
246 htmlspecialchars( $term ),
248 $this->msg( 'searchbutton' )->escaped()
250 Xml
::closeElement( 'fieldset' )
257 $title = Title
::newFromText( $term );
258 $showSuggestion = $title === null ||
!$title->isKnown();
259 $search->setShowSuggestion( $showSuggestion );
261 // fetch search results
262 $rewritten = $search->replacePrefixes( $term );
264 $titleMatches = $search->searchTitle( $rewritten );
265 $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 # mirror Go/Search behavior of original request ..
276 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
278 if ( $this->fulltext
!= null ) {
279 $didYouMeanParams['fulltext'] = $this->fulltext
;
282 $stParams = array_merge(
284 $this->powerSearchOptions()
287 $suggestionSnippet = $textMatches->getSuggestionSnippet();
289 if ( $suggestionSnippet == '' ) {
290 $suggestionSnippet = null;
293 $suggestLink = Linker
::linkKnown(
294 $this->getPageTitle(),
300 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
301 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
304 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
305 # Hook requested termination
309 // start rendering the page
314 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
316 'action' => wfScript(),
321 // Get number of results
322 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
323 if ( $titleMatches ) {
324 $titleMatchesNum = $titleMatches->numRows();
325 $numTitleMatches = $titleMatches->getTotalHits();
327 if ( $textMatches ) {
328 $textMatchesNum = $textMatches->numRows();
329 $numTextMatches = $textMatches->getTotalHits();
331 $num = $titleMatchesNum +
$textMatchesNum;
332 $totalRes = $numTitleMatches +
$numTextMatches;
335 # This is an awful awful ID name. It's not a table, but we
336 # named it poorly from when this was a table so now we're
338 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
339 $this->shortDialog( $term, $num, $totalRes ) .
340 Xml
::closeElement( 'div' ) .
341 $this->formHeader( $term ) .
342 Xml
::closeElement( 'form' )
345 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
346 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
347 // Empty query -- straight view of search form
351 $out->addHtml( "<div class='searchresults'>" );
355 if ( $num ||
$this->offset
) {
356 // Show the create link ahead
357 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
358 if ( $totalRes > $this->limit ||
$this->offset
) {
359 if ( $this->searchEngineType
!== null ) {
360 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
362 $prevnext = $this->getLanguage()->viewPrevNext(
363 $this->getPageTitle(),
366 $this->powerSearchOptions() +
array( 'search' => $term ),
367 $this->limit +
$this->offset
>= $totalRes
370 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
372 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
375 $out->parserOptions()->setEditSection( false );
376 if ( $titleMatches ) {
377 if ( $numTitleMatches > 0 ) {
378 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
379 $out->addHTML( $this->showMatches( $titleMatches ) );
381 $titleMatches->free();
383 if ( $textMatches && !$textStatus ) {
384 // output appropriate heading
385 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
386 // if no title matches the heading is redundant
387 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
390 // show interwiki results if any
391 if ( $textMatches->hasInterwikiResults() ) {
392 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
395 if ( $numTextMatches > 0 ) {
396 $out->addHTML( $this->showMatches( $textMatches ) );
399 $textMatches->free();
403 $out->addHTML( '<div class="error">' .
404 $textStatus->getMessage( 'search-error' ) . '</div>' );
406 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
407 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
408 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
411 $out->addHtml( "</div>" );
414 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
419 * @param Title $title
420 * @param int $num The number of search results found
421 * @param null|SearchResultSet $titleMatches Results from title search
422 * @param null|SearchResultSet $textMatches Results from text search
424 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
425 // show direct page/create link if applicable
427 // Check DBkey !== '' in case of fragment link only.
428 if ( is_null( $title ) ||
$title->getDBkey() === ''
429 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
430 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
433 // preserve the paragraph for margins etc...
434 $this->getOutput()->addHtml( '<p></p>' );
439 $linkClass = 'mw-search-createlink';
440 if ( $title->isKnown() ) {
441 $messageName = 'searchmenu-exists';
442 $linkClass = 'mw-search-exists';
443 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
444 $messageName = 'searchmenu-new';
446 $messageName = 'searchmenu-new-nocreate';
450 wfEscapeWikiText( $title->getPrefixedText() ),
451 Message
::numParam( $num )
453 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
455 // Extensions using the hook might still return an empty $messageName
456 if ( $messageName ) {
457 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
459 // preserve the paragraph for margins etc...
460 $this->getOutput()->addHtml( '<p></p>' );
465 * @param string $term
467 protected function setupPage( $term ) {
468 # Should advanced UI be used?
469 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
470 $out = $this->getOutput();
471 if ( strval( $term ) !== '' ) {
472 $out->setPageTitle( $this->msg( 'searchresults' ) );
473 $out->setHTMLTitle( $this->msg( 'pagetitle' )
474 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
475 ->inContentLanguage()->text()
478 // add javascript specific to special:search
479 $out->addModules( 'mediawiki.special.search' );
483 * Extract "power search" namespace settings from the request object,
484 * returning a list of index numbers to search.
486 * @param WebRequest $request
489 protected function powerSearch( &$request ) {
491 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
492 if ( $request->getCheck( 'ns' . $ns ) ) {
501 * Reconstruct the 'power search' options for links
505 protected function powerSearchOptions() {
507 if ( $this->profile
!== 'advanced' ) {
508 $opt['profile'] = $this->profile
;
510 foreach ( $this->namespaces
as $n ) {
515 return $opt +
$this->extraParams
;
519 * Save namespace preferences when we're supposed to
521 * @return bool Whether we wrote something
523 protected function saveNamespaces() {
524 $user = $this->getUser();
525 $request = $this->getRequest();
527 if ( $user->isLoggedIn() &&
528 $user->matchEditToken(
529 $request->getVal( 'nsRemember' ),
534 // Reset namespace preferences: namespaces are not searched
535 // when they're not mentioned in the URL parameters.
536 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
537 $user->setOption( 'searchNs' . $n, false );
539 // The request parameters include all the namespaces to be searched.
540 // Even if they're the same as an existing profile, they're not eaten.
541 foreach ( $this->namespaces
as $n ) {
542 $user->setOption( 'searchNs' . $n, true );
545 $user->saveSettings();
553 * Show whole set of results
555 * @param SearchResultSet $matches
559 protected function showMatches( &$matches ) {
562 $profile = new ProfileSection( __METHOD__
);
563 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
565 $out = "<ul class='mw-search-results'>\n";
566 $result = $matches->next();
568 $out .= $this->showHit( $result, $terms );
569 $result = $matches->next();
573 // convert the whole thing to desired language variant
574 $out = $wgContLang->convert( $out );
580 * Format a single hit result
582 * @param SearchResult $result
583 * @param array $terms Terms to highlight
587 protected function showHit( $result, $terms ) {
588 $profile = new ProfileSection( __METHOD__
);
590 if ( $result->isBrokenTitle() ) {
594 $title = $result->getTitle();
596 $titleSnippet = $result->getTitleSnippet( $terms );
598 if ( $titleSnippet == '' ) {
599 $titleSnippet = null;
602 $link_t = clone $title;
604 wfRunHooks( 'ShowSearchHitTitle',
605 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
607 $link = Linker
::linkKnown(
612 //If page content is not readable, just return the title.
613 //This is not quite safe, but better than showing excerpts from non-readable pages
614 //Note that hiding the entry entirely would screw up paging.
615 if ( !$title->userCan( 'read', $this->getUser() ) ) {
616 return "<li>{$link}</li>\n";
619 // If the page doesn't *exist*... our search index is out of date.
620 // The least confusing at this point is to drop the result.
621 // You may get less results, but... oh well. :P
622 if ( $result->isMissingRevision() ) {
626 // format redirects / relevant sections
627 $redirectTitle = $result->getRedirectTitle();
628 $redirectText = $result->getRedirectSnippet( $terms );
629 $sectionTitle = $result->getSectionTitle();
630 $sectionText = $result->getSectionSnippet( $terms );
633 if ( !is_null( $redirectTitle ) ) {
634 if ( $redirectText == '' ) {
635 $redirectText = null;
638 $redirect = "<span class='searchalttitle'>" .
639 $this->msg( 'search-redirect' )->rawParams(
640 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
646 if ( !is_null( $sectionTitle ) ) {
647 if ( $sectionText == '' ) {
651 $section = "<span class='searchalttitle'>" .
652 $this->msg( 'search-section' )->rawParams(
653 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
657 // format text extract
658 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
660 $lang = $this->getLanguage();
662 // format description
663 $byteSize = $result->getByteSize();
664 $wordCount = $result->getWordCount();
665 $timestamp = $result->getTimestamp();
666 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
667 ->numParams( $wordCount )->escaped();
669 if ( $title->getNamespace() == NS_CATEGORY
) {
670 $cat = Category
::newFromTitle( $title );
671 $size = $this->msg( 'search-result-category-size' )
672 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
676 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
678 // link to related articles if supported
680 if ( $result->hasRelated() ) {
681 $stParams = array_merge(
682 $this->powerSearchOptions(),
684 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
685 ':' . $title->getPrefixedText(),
686 'fulltext' => $this->msg( 'search' )->text()
690 $related = ' -- ' . Linker
::linkKnown(
691 $this->getPageTitle(),
692 $this->msg( 'search-relatedarticle' )->text(),
699 // Include a thumbnail for media files...
700 if ( $title->getNamespace() == NS_FILE
) {
701 $img = $result->getFile();
702 $img = $img ?
: wfFindFile( $title );
703 if ( $result->isFileMatch() ) {
704 $fileMatch = "<span class='searchalttitle'>" .
705 $this->msg( 'search-file-match' )->escaped() . "</span>";
708 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
710 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
711 // Float doesn't seem to interact well with the bullets.
712 // Table messes up vertical alignment of the bullets.
713 // Bullets are therefore disabled (didn't look great anyway).
715 '<table class="searchResultImage">' .
717 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
718 $thumb->toHtml( array( 'desc-link' => true ) ) .
720 '<td style="vertical-align: top;">' .
721 "{$link} {$redirect} {$section} {$fileMatch}" .
723 "<div class='mw-search-result-data'>{$desc} - {$date}{$related}</div>" .
735 if ( wfRunHooks( 'ShowSearchHit', array(
736 $this, $result, $terms,
737 &$link, &$redirect, &$section, &$extract,
738 &$score, &$size, &$date, &$related,
741 $html = "<li><div class='mw-search-result-heading'>" .
742 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
743 "<div class='mw-search-result-data'>{$size} - {$date}{$related}</div>" .
751 * Show results from other wikis
753 * @param SearchResultSet|array $matches
754 * @param string $query
758 protected function showInterwiki( $matches, $query ) {
760 $profile = new ProfileSection( __METHOD__
);
762 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
763 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
764 $out .= "<ul class='mw-search-iwresults'>\n";
766 // work out custom project captions
767 $customCaptions = array();
768 // format per line <iwprefix>:<caption>
769 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
770 foreach ( $customLines as $line ) {
771 $parts = explode( ":", $line, 2 );
772 if ( count( $parts ) == 2 ) { // validate line
773 $customCaptions[$parts[0]] = $parts[1];
777 if ( !is_array( $matches ) ) {
778 $matches = array( $matches );
781 foreach ( $matches as $set ) {
783 $result = $set->next();
785 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
786 $prev = $result->getInterwikiPrefix();
787 $result = $set->next();
791 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
792 $out .= "</ul></div>\n";
794 // convert the whole thing to desired language variant
795 $out = $wgContLang->convert( $out );
801 * Show single interwiki link
803 * @param SearchResult $result
804 * @param string $lastInterwiki
805 * @param string $query
806 * @param array $customCaptions Interwiki prefix -> caption
810 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
811 $profile = new ProfileSection( __METHOD__
);
813 if ( $result->isBrokenTitle() ) {
817 $title = $result->getTitle();
819 $titleSnippet = $result->getTitleSnippet();
821 if ( $titleSnippet == '' ) {
822 $titleSnippet = null;
825 $link = Linker
::linkKnown(
830 // format redirect if any
831 $redirectTitle = $result->getRedirectTitle();
832 $redirectText = $result->getRedirectSnippet();
834 if ( !is_null( $redirectTitle ) ) {
835 if ( $redirectText == '' ) {
836 $redirectText = null;
839 $redirect = "<span class='searchalttitle'>" .
840 $this->msg( 'search-redirect' )->rawParams(
841 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
846 // display project name
847 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
848 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
849 // captions from 'search-interwiki-custom'
850 $caption = $customCaptions[$title->getInterwiki()];
852 // default is to show the hostname of the other wiki which might suck
853 // if there are many wikis on one hostname
854 $parsed = wfParseUrl( $title->getFullURL() );
855 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
857 // "more results" link (special page stuff could be localized, but we might not know target lang)
858 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
859 $searchLink = Linker
::linkKnown(
861 $this->msg( 'search-interwiki-more' )->text(),
865 'fulltext' => 'Search'
868 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
869 {$searchLink}</span>{$caption}</div>\n<ul>";
872 $out .= "<li>{$link} {$redirect}</li>\n";
878 * Generates the power search box at [[Special:Search]]
880 * @param string $term Search term
882 * @return string HTML form
884 protected function powerSearchBox( $term, $opts ) {
887 // Groups namespaces into rows according to subject
889 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
890 $subject = MWNamespace
::getSubject( $namespace );
891 if ( !array_key_exists( $subject, $rows ) ) {
892 $rows[$subject] = "";
895 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
897 $name = $this->msg( 'blanknamespace' )->text();
901 Xml
::openElement( 'td' ) .
905 "mw-search-ns{$namespace}",
906 in_array( $namespace, $this->namespaces
)
908 Xml
::closeElement( 'td' );
911 $rows = array_values( $rows );
912 $numRows = count( $rows );
914 // Lays out namespaces in multiple floating two-column tables so they'll
915 // be arranged nicely while still accommodating different screen widths
916 $namespaceTables = '';
917 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
918 $namespaceTables .= Xml
::openElement(
920 array( 'cellpadding' => 0, 'cellspacing' => 0 )
923 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
924 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
927 $namespaceTables .= Xml
::closeElement( 'table' );
930 $showSections = array( 'namespaceTables' => $namespaceTables );
932 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
935 foreach ( $opts as $key => $value ) {
936 $hidden .= Html
::hidden( $key, $value );
939 # Stuff to feed saveNamespaces()
941 $user = $this->getUser();
942 if ( $user->isLoggedIn() ) {
943 $remember .= Xml
::checkLabel(
944 wfMessage( 'powersearch-remember' )->text(),
946 'mw-search-powersearch-remember',
948 // The token goes here rather than in a hidden field so it
949 // is only sent when necessary (not every form submission).
950 array( 'value' => $user->getEditToken(
957 // Return final output
958 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
959 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
960 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
961 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
962 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
963 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
965 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
967 Xml
::closeElement( 'fieldset' );
973 protected function getSearchProfiles() {
974 // Builds list of Search Types (profiles)
975 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
979 'message' => 'searchprofile-articles',
980 'tooltip' => 'searchprofile-articles-tooltip',
981 'namespaces' => SearchEngine
::defaultNamespaces(),
982 'namespace-messages' => SearchEngine
::namespacesAsText(
983 SearchEngine
::defaultNamespaces()
987 'message' => 'searchprofile-images',
988 'tooltip' => 'searchprofile-images-tooltip',
989 'namespaces' => array( NS_FILE
),
992 'message' => 'searchprofile-everything',
993 'tooltip' => 'searchprofile-everything-tooltip',
994 'namespaces' => $nsAllSet,
997 'message' => 'searchprofile-advanced',
998 'tooltip' => 'searchprofile-advanced-tooltip',
999 'namespaces' => self
::NAMESPACES_CURRENT
,
1003 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1005 foreach ( $profiles as &$data ) {
1006 if ( !is_array( $data['namespaces'] ) ) {
1009 sort( $data['namespaces'] );
1016 * @param string $term
1019 protected function formHeader( $term ) {
1020 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1023 if ( $this->startsWithImage( $term ) ) {
1025 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1028 $profiles = $this->getSearchProfiles();
1029 $lang = $this->getLanguage();
1031 // Outputs XML for Search Types
1032 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1033 $out .= Xml
::openElement( 'ul' );
1034 foreach ( $profiles as $id => $profile ) {
1035 if ( !isset( $profile['parameters'] ) ) {
1036 $profile['parameters'] = array();
1038 $profile['parameters']['profile'] = $id;
1040 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1041 $lang->commaList( $profile['namespace-messages'] ) : null;
1045 'class' => $this->profile
=== $id ?
'current' : 'normal'
1047 $this->makeSearchLink(
1050 $this->msg( $profile['message'] )->text(),
1051 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1052 $profile['parameters']
1056 $out .= Xml
::closeElement( 'ul' );
1057 $out .= Xml
::closeElement( 'div' );
1058 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1059 $out .= Xml
::closeElement( 'div' );
1063 $opts['profile'] = $this->profile
;
1065 if ( $this->profile
=== 'advanced' ) {
1066 $out .= $this->powerSearchBox( $term, $opts );
1069 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1077 * @param string $term
1078 * @param int $resultsShown
1079 * @param int $totalNum
1082 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1083 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1084 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1086 $out .= Html
::input( 'search', $term, 'search', array(
1087 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1090 'class' => 'mw-ui-input mw-ui-input-inline',
1092 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1093 $out .= Xml
::submitButton(
1094 $this->msg( 'searchbutton' )->text(),
1095 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1099 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1100 $top = $this->msg( 'showingresultsheader' )
1101 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1102 ->params( wfEscapeWikiText( $term ) )
1103 ->numParams( $resultsShown )
1105 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1106 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1109 return $out . $this->didYouMeanHtml
;
1113 * Make a search link with some target namespaces
1115 * @param string $term
1116 * @param array $namespaces Ignored
1117 * @param string $label Link's text
1118 * @param string $tooltip Link's tooltip
1119 * @param array $params Query string parameters
1120 * @return string HTML fragment
1122 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1124 foreach ( $namespaces as $n ) {
1125 $opt['ns' . $n] = 1;
1128 $stParams = array_merge(
1131 'fulltext' => $this->msg( 'search' )->text()
1136 return Xml
::element(
1139 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1147 * Check if query starts with image: prefix
1149 * @param string $term The string to check
1152 protected function startsWithImage( $term ) {
1155 $parts = explode( ':', $term );
1156 if ( count( $parts ) > 1 ) {
1157 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1164 * Check if query starts with all: prefix
1166 * @param string $term The string to check
1169 protected function startsWithAll( $term ) {
1171 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1173 $parts = explode( ':', $term );
1174 if ( count( $parts ) > 1 ) {
1175 return $parts[0] == $allkeyword;
1184 * @return SearchEngine
1186 public function getSearchEngine() {
1187 if ( $this->searchEngine
=== null ) {
1188 $this->searchEngine
= $this->searchEngineType ?
1189 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1192 return $this->searchEngine
;
1196 * Current search profile.
1197 * @return null|string
1199 function getProfile() {
1200 return $this->profile
;
1204 * Current namespaces.
1207 function getNamespaces() {
1208 return $this->namespaces
;
1212 * Users of hook SpecialSearchSetupEngine can use this to
1213 * add more params to links to not lose selection when
1214 * user navigates search results.
1217 * @param string $key
1218 * @param mixed $value
1220 public function setExtraParam( $key, $value ) {
1221 $this->extraParams
[$key] = $value;
1224 protected function getGroupName() {