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 ) {
542 $user->setOption( 'searchNs' . $n, false );
544 // The request parameters include all the namespaces we just searched.
545 // Even if they're the same as an existing profile, they're not eaten.
546 foreach ( $this->namespaces
as $n ) {
547 $user->setOption( 'searchNs' . $n, true );
550 $user->saveSettings();
558 * Show whole set of results
560 * @param SearchResultSet $matches
564 protected function showMatches( &$matches ) {
567 $profile = new ProfileSection( __METHOD__
);
568 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
570 $out = "<ul class='mw-search-results'>\n";
571 $result = $matches->next();
573 $out .= $this->showHit( $result, $terms );
574 $result = $matches->next();
578 // convert the whole thing to desired language variant
579 $out = $wgContLang->convert( $out );
585 * Format a single hit result
587 * @param SearchResult $result
588 * @param array $terms Terms to highlight
592 protected function showHit( $result, $terms ) {
593 $profile = new ProfileSection( __METHOD__
);
595 if ( $result->isBrokenTitle() ) {
599 $title = $result->getTitle();
601 $titleSnippet = $result->getTitleSnippet( $terms );
603 if ( $titleSnippet == '' ) {
604 $titleSnippet = null;
607 $link_t = clone $title;
609 wfRunHooks( 'ShowSearchHitTitle',
610 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
612 $link = Linker
::linkKnown(
617 //If page content is not readable, just return the title.
618 //This is not quite safe, but better than showing excerpts from non-readable pages
619 //Note that hiding the entry entirely would screw up paging.
620 if ( !$title->userCan( 'read', $this->getUser() ) ) {
621 return "<li>{$link}</li>\n";
624 // If the page doesn't *exist*... our search index is out of date.
625 // The least confusing at this point is to drop the result.
626 // You may get less results, but... oh well. :P
627 if ( $result->isMissingRevision() ) {
631 // format redirects / relevant sections
632 $redirectTitle = $result->getRedirectTitle();
633 $redirectText = $result->getRedirectSnippet( $terms );
634 $sectionTitle = $result->getSectionTitle();
635 $sectionText = $result->getSectionSnippet( $terms );
638 if ( !is_null( $redirectTitle ) ) {
639 if ( $redirectText == '' ) {
640 $redirectText = null;
643 $redirect = "<span class='searchalttitle'>" .
644 $this->msg( 'search-redirect' )->rawParams(
645 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
651 if ( !is_null( $sectionTitle ) ) {
652 if ( $sectionText == '' ) {
656 $section = "<span class='searchalttitle'>" .
657 $this->msg( 'search-section' )->rawParams(
658 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
662 // format text extract
663 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
665 $lang = $this->getLanguage();
668 if ( is_null( $result->getScore() ) ) {
669 // Search engine doesn't report scoring info
672 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
673 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
677 // format description
678 $byteSize = $result->getByteSize();
679 $wordCount = $result->getWordCount();
680 $timestamp = $result->getTimestamp();
681 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
682 ->numParams( $wordCount )->escaped();
684 if ( $title->getNamespace() == NS_CATEGORY
) {
685 $cat = Category
::newFromTitle( $title );
686 $size = $this->msg( 'search-result-category-size' )
687 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
691 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
693 // link to related articles if supported
695 if ( $result->hasRelated() ) {
696 $stParams = array_merge(
697 $this->powerSearchOptions(),
699 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
700 ':' . $title->getPrefixedText(),
701 'fulltext' => $this->msg( 'search' )->text()
705 $related = ' -- ' . Linker
::linkKnown(
706 $this->getPageTitle(),
707 $this->msg( 'search-relatedarticle' )->text(),
714 // Include a thumbnail for media files...
715 if ( $title->getNamespace() == NS_FILE
) {
716 $img = $result->getFile();
717 $img = $img ?
: wfFindFile( $title );
718 if ( $result->isFileMatch() ) {
719 $fileMatch = "<span class='searchalttitle'>" .
720 $this->msg( 'search-file-match' )->escaped() . "</span>";
723 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
725 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
726 // Float doesn't seem to interact well with the bullets.
727 // Table messes up vertical alignment of the bullets.
728 // Bullets are therefore disabled (didn't look great anyway).
730 '<table class="searchResultImage">' .
732 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
733 $thumb->toHtml( array( 'desc-link' => true ) ) .
735 '<td style="vertical-align: top;">' .
736 "{$link} {$fileMatch}" .
738 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
749 if ( wfRunHooks( 'ShowSearchHit', array(
750 $this, $result, $terms,
751 &$link, &$redirect, &$section, &$extract,
752 &$score, &$size, &$date, &$related,
755 $html = "<li><div class='mw-search-result-heading'>" .
756 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
757 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
765 * Show results from other wikis
767 * @param SearchResultSet|array $matches
768 * @param string $query
772 protected function showInterwiki( $matches, $query ) {
774 $profile = new ProfileSection( __METHOD__
);
776 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
777 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
778 $out .= "<ul class='mw-search-iwresults'>\n";
780 // work out custom project captions
781 $customCaptions = array();
782 // format per line <iwprefix>:<caption>
783 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
784 foreach ( $customLines as $line ) {
785 $parts = explode( ":", $line, 2 );
786 if ( count( $parts ) == 2 ) { // validate line
787 $customCaptions[$parts[0]] = $parts[1];
791 if ( !is_array( $matches ) ) {
792 $matches = array( $matches );
795 foreach ( $matches as $set ) {
797 $result = $set->next();
799 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
800 $prev = $result->getInterwikiPrefix();
801 $result = $set->next();
805 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
806 $out .= "</ul></div>\n";
808 // convert the whole thing to desired language variant
809 $out = $wgContLang->convert( $out );
815 * Show single interwiki link
817 * @param SearchResult $result
818 * @param string $lastInterwiki
819 * @param string $query
820 * @param array $customCaptions iw prefix -> caption
824 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
825 $profile = new ProfileSection( __METHOD__
);
827 if ( $result->isBrokenTitle() ) {
831 $title = $result->getTitle();
833 $titleSnippet = $result->getTitleSnippet();
835 if ( $titleSnippet == '' ) {
836 $titleSnippet = null;
839 $link = Linker
::linkKnown(
844 // format redirect if any
845 $redirectTitle = $result->getRedirectTitle();
846 $redirectText = $result->getRedirectSnippet();
848 if ( !is_null( $redirectTitle ) ) {
849 if ( $redirectText == '' ) {
850 $redirectText = null;
853 $redirect = "<span class='searchalttitle'>" .
854 $this->msg( 'search-redirect' )->rawParams(
855 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
860 // display project name
861 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
862 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
863 // captions from 'search-interwiki-custom'
864 $caption = $customCaptions[$title->getInterwiki()];
866 // default is to show the hostname of the other wiki which might suck
867 // if there are many wikis on one hostname
868 $parsed = wfParseUrl( $title->getFullURL() );
869 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
871 // "more results" link (special page stuff could be localized, but we might not know target lang)
872 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
873 $searchLink = Linker
::linkKnown(
875 $this->msg( 'search-interwiki-more' )->text(),
879 'fulltext' => 'Search'
882 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
883 {$searchLink}</span>{$caption}</div>\n<ul>";
886 $out .= "<li>{$link} {$redirect}</li>\n";
892 * @param string $profile
893 * @param string $term
896 protected function getProfileForm( $profile, $term ) {
899 $opts['profile'] = $this->profile
;
901 if ( $profile === 'advanced' ) {
902 return $this->powerSearchBox( $term, $opts );
905 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
912 * Generates the power search box at [[Special:Search]]
914 * @param string $term Search term
916 * @return string HTML form
918 protected function powerSearchBox( $term, $opts ) {
921 // Groups namespaces into rows according to subject
923 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
924 $subject = MWNamespace
::getSubject( $namespace );
925 if ( !array_key_exists( $subject, $rows ) ) {
926 $rows[$subject] = "";
929 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
931 $name = $this->msg( 'blanknamespace' )->text();
936 'td', array( 'style' => 'white-space: nowrap' )
941 "mw-search-ns{$namespace}",
942 in_array( $namespace, $this->namespaces
)
944 Xml
::closeElement( 'td' );
947 $rows = array_values( $rows );
948 $numRows = count( $rows );
950 // Lays out namespaces in multiple floating two-column tables so they'll
951 // be arranged nicely while still accommodating different screen widths
952 $namespaceTables = '';
953 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
954 $namespaceTables .= Xml
::openElement(
956 array( 'cellpadding' => 0, 'cellspacing' => 0 )
959 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
960 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
963 $namespaceTables .= Xml
::closeElement( 'table' );
966 $showSections = array( 'namespaceTables' => $namespaceTables );
968 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
971 foreach ( $opts as $key => $value ) {
972 $hidden .= Html
::hidden( $key, $value );
975 # Stuff to feed saveNamespaces()
977 $user = $this->getUser();
978 if ( $user->isLoggedIn() ) {
979 $remember .= Html
::hidden( 'nsToken', $user->getEditToken() ) .
981 wfMessage( 'powersearch-remember' )->text(),
983 'mw-search-powersearch-remember',
988 // Return final output
989 return Xml
::openElement(
991 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
993 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
994 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
995 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
996 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
997 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
999 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1001 Xml
::closeElement( 'fieldset' );
1007 protected function getSearchProfiles() {
1008 // Builds list of Search Types (profiles)
1009 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1013 'message' => 'searchprofile-articles',
1014 'tooltip' => 'searchprofile-articles-tooltip',
1015 'namespaces' => SearchEngine
::defaultNamespaces(),
1016 'namespace-messages' => SearchEngine
::namespacesAsText(
1017 SearchEngine
::defaultNamespaces()
1021 'message' => 'searchprofile-images',
1022 'tooltip' => 'searchprofile-images-tooltip',
1023 'namespaces' => array( NS_FILE
),
1026 'message' => 'searchprofile-everything',
1027 'tooltip' => 'searchprofile-everything-tooltip',
1028 'namespaces' => $nsAllSet,
1030 'advanced' => array(
1031 'message' => 'searchprofile-advanced',
1032 'tooltip' => 'searchprofile-advanced-tooltip',
1033 'namespaces' => self
::NAMESPACES_CURRENT
,
1037 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1039 foreach ( $profiles as &$data ) {
1040 if ( !is_array( $data['namespaces'] ) ) {
1043 sort( $data['namespaces'] );
1050 * @param string $term
1051 * @param int $resultsShown
1052 * @param int $totalNum
1055 protected function formHeader( $term, $resultsShown, $totalNum ) {
1056 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1059 if ( $this->startsWithImage( $term ) ) {
1061 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1064 $profiles = $this->getSearchProfiles();
1065 $lang = $this->getLanguage();
1067 // Outputs XML for Search Types
1068 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1069 $out .= Xml
::openElement( 'ul' );
1070 foreach ( $profiles as $id => $profile ) {
1071 if ( !isset( $profile['parameters'] ) ) {
1072 $profile['parameters'] = array();
1074 $profile['parameters']['profile'] = $id;
1076 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1077 $lang->commaList( $profile['namespace-messages'] ) : null;
1081 'class' => $this->profile
=== $id ?
'current' : 'normal'
1083 $this->makeSearchLink(
1086 $this->msg( $profile['message'] )->text(),
1087 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1088 $profile['parameters']
1092 $out .= Xml
::closeElement( 'ul' );
1093 $out .= Xml
::closeElement( 'div' );
1096 if ( $resultsShown > 0 ) {
1097 if ( $totalNum > 0 ) {
1098 $top = $this->msg( 'showingresultsheader' )
1099 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1100 ->params( wfEscapeWikiText( $term ) )
1101 ->numParams( $resultsShown )
1103 } elseif ( $resultsShown >= $this->limit
) {
1104 $top = $this->msg( 'showingresults' )
1105 ->numParams( $this->limit
, $this->offset +
1 )
1108 $top = $this->msg( 'showingresultsnum' )
1109 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1112 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1113 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1117 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1118 $out .= Xml
::closeElement( 'div' );
1124 * @param string $term
1127 protected function shortDialog( $term ) {
1128 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1129 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1131 $out .= Html
::input( 'search', $term, 'search', array(
1132 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1135 'class' => 'mw-ui-input',
1137 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1138 $out .= Xml
::submitButton(
1139 $this->msg( 'searchbutton' )->text(),
1140 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1143 return $out . $this->didYouMeanHtml
;
1147 * Make a search link with some target namespaces
1149 * @param string $term
1150 * @param array $namespaces Ignored
1151 * @param string $label Link's text
1152 * @param string $tooltip Link's tooltip
1153 * @param array $params Query string parameters
1154 * @return string HTML fragment
1156 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1158 foreach ( $namespaces as $n ) {
1159 $opt['ns' . $n] = 1;
1162 $stParams = array_merge(
1165 'fulltext' => $this->msg( 'search' )->text()
1170 return Xml
::element(
1173 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1181 * Check if query starts with image: prefix
1183 * @param string $term The string to check
1186 protected function startsWithImage( $term ) {
1189 $parts = explode( ':', $term );
1190 if ( count( $parts ) > 1 ) {
1191 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1198 * Check if query starts with all: prefix
1200 * @param string $term The string to check
1203 protected function startsWithAll( $term ) {
1205 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1207 $parts = explode( ':', $term );
1208 if ( count( $parts ) > 1 ) {
1209 return $parts[0] == $allkeyword;
1218 * @return SearchEngine
1220 public function getSearchEngine() {
1221 if ( $this->searchEngine
=== null ) {
1222 $this->searchEngine
= $this->searchEngineType ?
1223 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1226 return $this->searchEngine
;
1230 * Current search profile.
1231 * @return null|string
1233 function getProfile() {
1234 return $this->profile
;
1238 * Current namespaces.
1241 function getNamespaces() {
1242 return $this->namespaces
;
1246 * Users of hook SpecialSearchSetupEngine can use this to
1247 * add more params to links to not lose selection when
1248 * user navigates search results.
1251 * @param string $key
1252 * @param mixed $value
1254 public function setExtraParam( $key, $value ) {
1255 $this->extraParams
[$key] = $value;
1258 protected function getGroupName() {