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'
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 $this->saveNamespaces();
213 $search->prefix
= $this->mPrefix
;
214 $term = $search->transformSearchTerm( $term );
216 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
218 $this->setupPage( $term );
220 $out = $this->getOutput();
222 if ( $wgDisableTextSearch ) {
223 if ( $wgSearchForwardUrl ) {
224 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
225 $out->redirect( $url );
228 Xml
::openElement( 'fieldset' ) .
229 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
232 array( 'class' => 'mw-searchdisabled' ),
233 $this->msg( 'searchdisabled' )->text()
235 $this->msg( 'googlesearch' )->rawParams(
236 htmlspecialchars( $term ),
238 $this->msg( 'searchbutton' )->escaped()
240 Xml
::closeElement( 'fieldset' )
247 $title = Title
::newFromText( $term );
248 $showSuggestion = $title === null ||
!$title->isKnown();
249 $search->setShowSuggestion( $showSuggestion );
251 // fetch search results
252 $rewritten = $search->replacePrefixes( $term );
254 $titleMatches = $search->searchTitle( $rewritten );
255 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
256 $textMatches = $search->searchText( $rewritten );
260 if ( $textMatches instanceof Status
) {
261 $textStatus = $textMatches;
265 // did you mean... suggestions
266 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
267 # mirror Go/Search behavior of original request ..
268 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
270 if ( $this->fulltext
!= null ) {
271 $didYouMeanParams['fulltext'] = $this->fulltext
;
274 $stParams = array_merge(
276 $this->powerSearchOptions()
279 $suggestionSnippet = $textMatches->getSuggestionSnippet();
281 if ( $suggestionSnippet == '' ) {
282 $suggestionSnippet = null;
285 $suggestLink = Linker
::linkKnown(
286 $this->getPageTitle(),
292 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
293 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
296 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
297 # Hook requested termination
301 // start rendering the page
306 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
308 'action' => $wgScript
313 # This is an awful awful ID name. It's not a table, but we
314 # named it poorly from when this was a table so now we're
316 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
317 $this->shortDialog( $term ) .
318 Xml
::closeElement( 'div' )
321 // Sometimes the search engine knows there are too many hits
322 if ( $titleMatches instanceof SearchResultTooMany
) {
323 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
328 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
329 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
330 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
331 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
332 $out->addHTML( '</form>' );
334 // Empty query -- straight view of search form
338 // Get number of results
339 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
340 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
341 // Total initial query matches (possible false positives)
342 $num = $titleMatchesNum +
$textMatchesNum;
344 // Get total actual results (after second filtering, if any)
345 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
346 $titleMatches->getTotalHits() : $titleMatchesNum;
347 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
348 $textMatches->getTotalHits() : $textMatchesNum;
350 // get total number of results if backend can calculate it
352 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
353 $totalRes +
= $titleMatches->getTotalHits();
355 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
356 $totalRes +
= $textMatches->getTotalHits();
359 // show number of results and current offset
360 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
361 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
363 $out->addHtml( Xml
::closeElement( 'form' ) );
364 $out->addHtml( "<div class='searchresults'>" );
368 if ( $num ||
$this->offset
) {
369 // Show the create link ahead
370 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
371 if ( $totalRes > $this->limit ||
$this->offset
) {
372 $prevnext = $this->getLanguage()->viewPrevNext(
373 $this->getPageTitle(),
376 $this->powerSearchOptions() +
array( 'search' => $term ),
377 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
380 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
382 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
385 $out->parserOptions()->setEditSection( false );
386 if ( $titleMatches ) {
387 if ( $numTitleMatches > 0 ) {
388 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
389 $out->addHTML( $this->showMatches( $titleMatches ) );
391 $titleMatches->free();
393 if ( $textMatches && !$textStatus ) {
394 // output appropriate heading
395 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
396 // if no title matches the heading is redundant
397 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
400 // show interwiki results if any
401 if ( $textMatches->hasInterwikiResults() ) {
402 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
405 if ( $numTextMatches > 0 ) {
406 $out->addHTML( $this->showMatches( $textMatches ) );
409 $textMatches->free();
413 $out->addHTML( '<div class="error">' .
414 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
416 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
417 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
418 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
421 $out->addHtml( "</div>" );
424 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
429 * @param Title $title
430 * @param int $num The number of search results found
431 * @param null|SearchResultSet $titleMatches Results from title search
432 * @param null|SearchResultSet $textMatches Results from text search
434 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
435 // show direct page/create link if applicable
437 // Check DBkey !== '' in case of fragment link only.
438 if ( is_null( $title ) ||
$title->getDBkey() === ''
439 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
440 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
443 // preserve the paragraph for margins etc...
444 $this->getOutput()->addHtml( '<p></p>' );
449 if ( $title->isKnown() ) {
450 $messageName = 'searchmenu-exists';
451 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
452 $messageName = 'searchmenu-new';
454 $messageName = 'searchmenu-new-nocreate';
458 wfEscapeWikiText( $title->getPrefixedText() ),
459 Message
::numParam( $num )
461 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
463 // Extensions using the hook might still return an empty $messageName
464 if ( $messageName ) {
465 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
467 // preserve the paragraph for margins etc...
468 $this->getOutput()->addHtml( '<p></p>' );
473 * @param string $term
475 protected function setupPage( $term ) {
476 # Should advanced UI be used?
477 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
478 $out = $this->getOutput();
479 if ( strval( $term ) !== '' ) {
480 $out->setPageTitle( $this->msg( 'searchresults' ) );
481 $out->setHTMLTitle( $this->msg( 'pagetitle' )
482 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
483 ->inContentLanguage()->text()
486 // add javascript specific to special:search
487 $out->addModules( 'mediawiki.special.search' );
491 * Extract "power search" namespace settings from the request object,
492 * returning a list of index numbers to search.
494 * @param WebRequest $request
497 protected function powerSearch( &$request ) {
499 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
500 if ( $request->getCheck( 'ns' . $ns ) ) {
509 * Reconstruct the 'power search' options for links
513 protected function powerSearchOptions() {
515 if ( $this->profile
!== 'advanced' ) {
516 $opt['profile'] = $this->profile
;
518 foreach ( $this->namespaces
as $n ) {
523 return $opt +
$this->extraParams
;
527 * Save namespace preferences when we're supposed to
529 * @return bool Whether we wrote something
531 protected function saveNamespaces() {
532 $user = $this->getUser();
533 $request = $this->getRequest();
535 if ( $user->isLoggedIn() &&
536 !is_null( $request->getVal( 'nsRemember' ) ) &&
537 $user->matchEditToken( $request->getVal( 'nsToken' ) )
539 // Reset namespace preferences: namespaces are not searched
540 // when they're not mentioned in the URL parameters.
541 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
543 $user->setOption( 'searchNs' . $n, false );
546 // The request parameters include all the namespaces we just searched.
547 // Even if they're the same as an existing profile, they're not eaten.
548 foreach ( $this->namespaces
as $n ) {
549 $user->setOption( 'searchNs' . $n, true );
552 $user->saveSettings();
560 * Show whole set of results
562 * @param SearchResultSet $matches
566 protected function showMatches( &$matches ) {
569 $profile = new ProfileSection( __METHOD__
);
570 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
572 $out = "<ul class='mw-search-results'>\n";
573 $result = $matches->next();
575 $out .= $this->showHit( $result, $terms );
576 $result = $matches->next();
580 // convert the whole thing to desired language variant
581 $out = $wgContLang->convert( $out );
587 * Format a single hit result
589 * @param SearchResult $result
590 * @param array $terms Terms to highlight
594 protected function showHit( $result, $terms ) {
595 $profile = new ProfileSection( __METHOD__
);
597 if ( $result->isBrokenTitle() ) {
601 $title = $result->getTitle();
603 $titleSnippet = $result->getTitleSnippet( $terms );
605 if ( $titleSnippet == '' ) {
606 $titleSnippet = null;
609 $link_t = clone $title;
611 wfRunHooks( 'ShowSearchHitTitle',
612 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
614 $link = Linker
::linkKnown(
619 //If page content is not readable, just return the title.
620 //This is not quite safe, but better than showing excerpts from non-readable pages
621 //Note that hiding the entry entirely would screw up paging.
622 if ( !$title->userCan( 'read', $this->getUser() ) ) {
623 return "<li>{$link}</li>\n";
626 // If the page doesn't *exist*... our search index is out of date.
627 // The least confusing at this point is to drop the result.
628 // You may get less results, but... oh well. :P
629 if ( $result->isMissingRevision() ) {
633 // format redirects / relevant sections
634 $redirectTitle = $result->getRedirectTitle();
635 $redirectText = $result->getRedirectSnippet( $terms );
636 $sectionTitle = $result->getSectionTitle();
637 $sectionText = $result->getSectionSnippet( $terms );
640 if ( !is_null( $redirectTitle ) ) {
641 if ( $redirectText == '' ) {
642 $redirectText = null;
645 $redirect = "<span class='searchalttitle'>" .
646 $this->msg( 'search-redirect' )->rawParams(
647 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
653 if ( !is_null( $sectionTitle ) ) {
654 if ( $sectionText == '' ) {
658 $section = "<span class='searchalttitle'>" .
659 $this->msg( 'search-section' )->rawParams(
660 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
664 // format text extract
665 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
667 $lang = $this->getLanguage();
670 if ( is_null( $result->getScore() ) ) {
671 // Search engine doesn't report scoring info
674 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
675 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
679 // format description
680 $byteSize = $result->getByteSize();
681 $wordCount = $result->getWordCount();
682 $timestamp = $result->getTimestamp();
683 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
684 ->numParams( $wordCount )->escaped();
686 if ( $title->getNamespace() == NS_CATEGORY
) {
687 $cat = Category
::newFromTitle( $title );
688 $size = $this->msg( 'search-result-category-size' )
689 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
693 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
695 // link to related articles if supported
697 if ( $result->hasRelated() ) {
698 $stParams = array_merge(
699 $this->powerSearchOptions(),
701 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
702 ':' . $title->getPrefixedText(),
703 'fulltext' => $this->msg( 'search' )->text()
707 $related = ' -- ' . Linker
::linkKnown(
708 $this->getPageTitle(),
709 $this->msg( 'search-relatedarticle' )->text(),
716 // Include a thumbnail for media files...
717 if ( $title->getNamespace() == NS_FILE
) {
718 $img = $result->getFile();
719 $img = $img ?
: wfFindFile( $title );
720 if ( $result->isFileMatch() ) {
721 $fileMatch = "<span class='searchalttitle'>" .
722 $this->msg( 'search-file-match' )->escaped() . "</span>";
725 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
727 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
728 // Float doesn't seem to interact well with the bullets.
729 // Table messes up vertical alignment of the bullets.
730 // Bullets are therefore disabled (didn't look great anyway).
732 '<table class="searchResultImage">' .
734 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
735 $thumb->toHtml( array( 'desc-link' => true ) ) .
737 '<td style="vertical-align: top;">' .
738 "{$link} {$fileMatch}" .
740 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
751 if ( wfRunHooks( 'ShowSearchHit', array(
752 $this, $result, $terms,
753 &$link, &$redirect, &$section, &$extract,
754 &$score, &$size, &$date, &$related,
757 $html = "<li><div class='mw-search-result-heading'>" .
758 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
759 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
767 * Show results from other wikis
769 * @param SearchResultSet|array $matches
770 * @param string $query
774 protected function showInterwiki( $matches, $query ) {
776 $profile = new ProfileSection( __METHOD__
);
778 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
779 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
780 $out .= "<ul class='mw-search-iwresults'>\n";
782 // work out custom project captions
783 $customCaptions = array();
784 // format per line <iwprefix>:<caption>
785 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
786 foreach ( $customLines as $line ) {
787 $parts = explode( ":", $line, 2 );
788 if ( count( $parts ) == 2 ) { // validate line
789 $customCaptions[$parts[0]] = $parts[1];
793 if ( !is_array( $matches ) ) {
794 $matches = array( $matches );
797 foreach ( $matches as $set ) {
799 $result = $set->next();
801 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
802 $prev = $result->getInterwikiPrefix();
803 $result = $set->next();
807 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
808 $out .= "</ul></div>\n";
810 // convert the whole thing to desired language variant
811 $out = $wgContLang->convert( $out );
817 * Show single interwiki link
819 * @param SearchResult $result
820 * @param string $lastInterwiki
821 * @param string $query
822 * @param array $customCaptions iw prefix -> caption
826 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
827 $profile = new ProfileSection( __METHOD__
);
829 if ( $result->isBrokenTitle() ) {
833 $title = $result->getTitle();
835 $titleSnippet = $result->getTitleSnippet();
837 if ( $titleSnippet == '' ) {
838 $titleSnippet = null;
841 $link = Linker
::linkKnown(
846 // format redirect if any
847 $redirectTitle = $result->getRedirectTitle();
848 $redirectText = $result->getRedirectSnippet();
850 if ( !is_null( $redirectTitle ) ) {
851 if ( $redirectText == '' ) {
852 $redirectText = null;
855 $redirect = "<span class='searchalttitle'>" .
856 $this->msg( 'search-redirect' )->rawParams(
857 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
862 // display project name
863 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
864 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
865 // captions from 'search-interwiki-custom'
866 $caption = $customCaptions[$title->getInterwiki()];
868 // default is to show the hostname of the other wiki which might suck
869 // if there are many wikis on one hostname
870 $parsed = wfParseUrl( $title->getFullURL() );
871 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
873 // "more results" link (special page stuff could be localized, but we might not know target lang)
874 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
875 $searchLink = Linker
::linkKnown(
877 $this->msg( 'search-interwiki-more' )->text(),
881 'fulltext' => 'Search'
884 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
885 {$searchLink}</span>{$caption}</div>\n<ul>";
888 $out .= "<li>{$link} {$redirect}</li>\n";
894 * @param string $profile
895 * @param string $term
898 protected function getProfileForm( $profile, $term ) {
901 $opts['profile'] = $this->profile
;
903 if ( $profile === 'advanced' ) {
904 return $this->powerSearchBox( $term, $opts );
907 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
914 * Generates the power search box at [[Special:Search]]
916 * @param string $term Search term
918 * @return string HTML form
920 protected function powerSearchBox( $term, $opts ) {
923 // Groups namespaces into rows according to subject
925 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
926 $subject = MWNamespace
::getSubject( $namespace );
927 if ( !array_key_exists( $subject, $rows ) ) {
928 $rows[$subject] = "";
931 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
933 $name = $this->msg( 'blanknamespace' )->text();
938 'td', array( 'style' => 'white-space: nowrap' )
943 "mw-search-ns{$namespace}",
944 in_array( $namespace, $this->namespaces
)
946 Xml
::closeElement( 'td' );
949 $rows = array_values( $rows );
950 $numRows = count( $rows );
952 // Lays out namespaces in multiple floating two-column tables so they'll
953 // be arranged nicely while still accommodating different screen widths
954 $namespaceTables = '';
955 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
956 $namespaceTables .= Xml
::openElement(
958 array( 'cellpadding' => 0, 'cellspacing' => 0 )
961 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
962 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
965 $namespaceTables .= Xml
::closeElement( 'table' );
968 $showSections = array( 'namespaceTables' => $namespaceTables );
970 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
973 foreach ( $opts as $key => $value ) {
974 $hidden .= Html
::hidden( $key, $value );
977 # Stuff to feed saveNamespaces()
979 $user = $this->getUser();
980 if ( $user->isLoggedIn() ) {
981 $remember .= Html
::hidden( 'nsToken', $user->getEditToken() ) .
983 wfMessage( 'powersearch-remember' )->text(),
985 'mw-search-powersearch-remember',
990 // Return final output
991 return Xml
::openElement(
993 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
995 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
996 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
997 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
998 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
999 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1001 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1003 Xml
::closeElement( 'fieldset' );
1009 protected function getSearchProfiles() {
1010 // Builds list of Search Types (profiles)
1011 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1015 'message' => 'searchprofile-articles',
1016 'tooltip' => 'searchprofile-articles-tooltip',
1017 'namespaces' => SearchEngine
::defaultNamespaces(),
1018 'namespace-messages' => SearchEngine
::namespacesAsText(
1019 SearchEngine
::defaultNamespaces()
1023 'message' => 'searchprofile-images',
1024 'tooltip' => 'searchprofile-images-tooltip',
1025 'namespaces' => array( NS_FILE
),
1028 'message' => 'searchprofile-everything',
1029 'tooltip' => 'searchprofile-everything-tooltip',
1030 'namespaces' => $nsAllSet,
1032 'advanced' => array(
1033 'message' => 'searchprofile-advanced',
1034 'tooltip' => 'searchprofile-advanced-tooltip',
1035 'namespaces' => self
::NAMESPACES_CURRENT
,
1039 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1041 foreach ( $profiles as &$data ) {
1042 if ( !is_array( $data['namespaces'] ) ) {
1045 sort( $data['namespaces'] );
1052 * @param string $term
1053 * @param int $resultsShown
1054 * @param int $totalNum
1057 protected function formHeader( $term, $resultsShown, $totalNum ) {
1058 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1061 if ( $this->startsWithImage( $term ) ) {
1063 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1066 $profiles = $this->getSearchProfiles();
1067 $lang = $this->getLanguage();
1069 // Outputs XML for Search Types
1070 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1071 $out .= Xml
::openElement( 'ul' );
1072 foreach ( $profiles as $id => $profile ) {
1073 if ( !isset( $profile['parameters'] ) ) {
1074 $profile['parameters'] = array();
1076 $profile['parameters']['profile'] = $id;
1078 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1079 $lang->commaList( $profile['namespace-messages'] ) : null;
1083 'class' => $this->profile
=== $id ?
'current' : 'normal'
1085 $this->makeSearchLink(
1088 $this->msg( $profile['message'] )->text(),
1089 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1090 $profile['parameters']
1094 $out .= Xml
::closeElement( 'ul' );
1095 $out .= Xml
::closeElement( 'div' );
1098 if ( $resultsShown > 0 ) {
1099 if ( $totalNum > 0 ) {
1100 $top = $this->msg( 'showingresultsheader' )
1101 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1102 ->params( wfEscapeWikiText( $term ) )
1103 ->numParams( $resultsShown )
1105 } elseif ( $resultsShown >= $this->limit
) {
1106 $top = $this->msg( 'showingresults' )
1107 ->numParams( $this->limit
, $this->offset +
1 )
1110 $top = $this->msg( 'showingresultsnum' )
1111 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1114 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1115 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1119 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1120 $out .= Xml
::closeElement( 'div' );
1126 * @param string $term
1129 protected function shortDialog( $term ) {
1130 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1131 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1133 $out .= Html
::input( 'search', $term, 'search', array(
1134 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1137 'class' => 'mw-ui-input',
1139 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1140 $out .= Xml
::submitButton(
1141 $this->msg( 'searchbutton' )->text(),
1142 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1145 return $out . $this->didYouMeanHtml
;
1149 * Make a search link with some target namespaces
1151 * @param string $term
1152 * @param array $namespaces Ignored
1153 * @param string $label Link's text
1154 * @param string $tooltip Link's tooltip
1155 * @param array $params Query string parameters
1156 * @return string HTML fragment
1158 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1160 foreach ( $namespaces as $n ) {
1161 $opt['ns' . $n] = 1;
1164 $stParams = array_merge(
1167 'fulltext' => $this->msg( 'search' )->text()
1172 return Xml
::element(
1175 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1183 * Check if query starts with image: prefix
1185 * @param string $term The string to check
1188 protected function startsWithImage( $term ) {
1191 $parts = explode( ':', $term );
1192 if ( count( $parts ) > 1 ) {
1193 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1200 * Check if query starts with all: prefix
1202 * @param string $term The string to check
1205 protected function startsWithAll( $term ) {
1207 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1209 $parts = explode( ':', $term );
1210 if ( count( $parts ) > 1 ) {
1211 return $parts[0] == $allkeyword;
1220 * @return SearchEngine
1222 public function getSearchEngine() {
1223 if ( $this->searchEngine
=== null ) {
1224 $this->searchEngine
= $this->searchEngineType ?
1225 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1228 return $this->searchEngine
;
1232 * Current search profile.
1233 * @return null|string
1235 function getProfile() {
1236 return $this->profile
;
1240 * Current namespaces.
1243 function getNamespaces() {
1244 return $this->namespaces
;
1248 * Users of hook SpecialSearchSetupEngine can use this to
1249 * add more params to links to not lose selection when
1250 * user navigates search results.
1253 * @param string $key
1254 * @param mixed $value
1256 public function setExtraParam( $key, $value ) {
1257 $this->extraParams
[$key] = $value;
1260 protected function getGroupName() {