d308681d8f9b8c1630b28702b0fdeee32338d91c
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 // Request an extra result to determine whether a "next page" link is useful
211 $search->setLimitOffset( $this->limit +
1, $this->offset
);
212 $search->setNamespaces( $this->namespaces
);
213 $this->saveNamespaces();
214 $search->prefix
= $this->mPrefix
;
215 $term = $search->transformSearchTerm( $term );
217 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
219 $this->setupPage( $term );
221 $out = $this->getOutput();
223 if ( $wgDisableTextSearch ) {
224 if ( $wgSearchForwardUrl ) {
225 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
226 $out->redirect( $url );
229 Xml
::openElement( 'fieldset' ) .
230 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
233 array( 'class' => 'mw-searchdisabled' ),
234 $this->msg( 'searchdisabled' )->text()
236 $this->msg( 'googlesearch' )->rawParams(
237 htmlspecialchars( $term ),
239 $this->msg( 'searchbutton' )->escaped()
241 Xml
::closeElement( 'fieldset' )
248 $title = Title
::newFromText( $term );
249 $showSuggestion = $title === null ||
!$title->isKnown();
250 $search->setShowSuggestion( $showSuggestion );
252 // fetch search results
253 $rewritten = $search->replacePrefixes( $term );
255 $titleMatches = $search->searchTitle( $rewritten );
256 if ( !( $titleMatches instanceof SearchResultTooMany
) ) {
257 $textMatches = $search->searchText( $rewritten );
261 if ( $textMatches instanceof Status
) {
262 $textStatus = $textMatches;
266 // did you mean... suggestions
267 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
268 # mirror Go/Search behavior of original request ..
269 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
271 if ( $this->fulltext
!= null ) {
272 $didYouMeanParams['fulltext'] = $this->fulltext
;
275 $stParams = array_merge(
277 $this->powerSearchOptions()
280 $suggestionSnippet = $textMatches->getSuggestionSnippet();
282 if ( $suggestionSnippet == '' ) {
283 $suggestionSnippet = null;
286 $suggestLink = Linker
::linkKnown(
287 $this->getPageTitle(),
293 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
294 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
297 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
298 # Hook requested termination
302 // start rendering the page
307 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
309 'action' => $wgScript
314 # This is an awful awful ID name. It's not a table, but we
315 # named it poorly from when this was a table so now we're
317 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
318 $this->shortDialog( $term ) .
319 Xml
::closeElement( 'div' )
322 // Sometimes the search engine knows there are too many hits
323 if ( $titleMatches instanceof SearchResultTooMany
) {
324 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
329 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
330 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
331 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
332 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
333 $out->addHTML( '</form>' );
335 // Empty query -- straight view of search form
339 // Get number of results
340 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
341 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
342 // Total initial query matches (possible false positives)
343 $num = $titleMatchesNum +
$textMatchesNum;
345 // Get total actual results (after second filtering, if any)
346 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
347 $titleMatches->getTotalHits() : $titleMatchesNum;
348 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
349 $textMatches->getTotalHits() : $textMatchesNum;
351 // get total number of results if backend can calculate it
353 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
354 $totalRes +
= $titleMatches->getTotalHits();
356 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
357 $totalRes +
= $textMatches->getTotalHits();
360 // show number of results and current offset
361 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
362 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
364 $out->addHtml( Xml
::closeElement( 'form' ) );
365 $out->addHtml( "<div class='searchresults'>" );
369 if ( $num ||
$this->offset
) {
370 // Show the create link ahead
371 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
372 if ( $totalRes > $this->limit ||
$this->offset
) {
373 $prevnext = $this->getLanguage()->viewPrevNext(
374 $this->getPageTitle(),
377 $this->powerSearchOptions() +
array( 'search' => $term ),
378 max( $titleMatchesNum, $textMatchesNum ) <= $this->limit
381 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
383 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
386 $out->parserOptions()->setEditSection( false );
387 if ( $titleMatches ) {
388 if ( $numTitleMatches > 0 ) {
389 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
390 $out->addHTML( $this->showMatches( $titleMatches ) );
392 $titleMatches->free();
394 if ( $textMatches && !$textStatus ) {
395 // output appropriate heading
396 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
397 // if no title matches the heading is redundant
398 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
401 // show interwiki results if any
402 if ( $textMatches->hasInterwikiResults() ) {
403 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
406 if ( $numTextMatches > 0 ) {
407 $out->addHTML( $this->showMatches( $textMatches ) );
410 $textMatches->free();
414 $out->addHTML( '<div class="error">' .
415 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
417 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
418 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
419 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
422 $out->addHtml( "</div>" );
425 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
430 * @param Title $title
431 * @param int $num The number of search results found
432 * @param null|SearchResultSet $titleMatches Results from title search
433 * @param null|SearchResultSet $textMatches Results from text search
435 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
436 // show direct page/create link if applicable
438 // Check DBkey !== '' in case of fragment link only.
439 if ( is_null( $title ) ||
$title->getDBkey() === ''
440 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
441 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
444 // preserve the paragraph for margins etc...
445 $this->getOutput()->addHtml( '<p></p>' );
450 if ( $title->isKnown() ) {
451 $messageName = 'searchmenu-exists';
452 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
453 $messageName = 'searchmenu-new';
455 $messageName = 'searchmenu-new-nocreate';
459 wfEscapeWikiText( $title->getPrefixedText() ),
460 Message
::numParam( $num )
462 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
464 // Extensions using the hook might still return an empty $messageName
465 if ( $messageName ) {
466 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
468 // preserve the paragraph for margins etc...
469 $this->getOutput()->addHtml( '<p></p>' );
474 * @param string $term
476 protected function setupPage( $term ) {
477 # Should advanced UI be used?
478 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
479 $out = $this->getOutput();
480 if ( strval( $term ) !== '' ) {
481 $out->setPageTitle( $this->msg( 'searchresults' ) );
482 $out->setHTMLTitle( $this->msg( 'pagetitle' )
483 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
484 ->inContentLanguage()->text()
487 // add javascript specific to special:search
488 $out->addModules( 'mediawiki.special.search' );
492 * Extract "power search" namespace settings from the request object,
493 * returning a list of index numbers to search.
495 * @param WebRequest $request
498 protected function powerSearch( &$request ) {
500 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
501 if ( $request->getCheck( 'ns' . $ns ) ) {
510 * Reconstruct the 'power search' options for links
514 protected function powerSearchOptions() {
516 if ( $this->profile
!== 'advanced' ) {
517 $opt['profile'] = $this->profile
;
519 foreach ( $this->namespaces
as $n ) {
524 return $opt +
$this->extraParams
;
528 * Save namespace preferences when we're supposed to
530 * @return bool Whether we wrote something
532 protected function saveNamespaces() {
533 $user = $this->getUser();
534 $request = $this->getRequest();
536 if ( $user->isLoggedIn() &&
537 !is_null( $request->getVal( 'nsRemember' ) ) &&
538 $user->matchEditToken( $request->getVal( 'nsToken' ) )
540 // Reset namespace preferences: namespaces are not searched
541 // when they're not mentioned in the URL parameters.
542 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
544 $user->setOption( 'searchNs' . $n, false );
547 // The request parameters include all the namespaces we just searched.
548 // Even if they're the same as an existing profile, they're not eaten.
549 foreach ( $this->namespaces
as $n ) {
550 $user->setOption( 'searchNs' . $n, true );
553 $user->saveSettings();
561 * Show whole set of results
563 * @param SearchResultSet $matches
567 protected function showMatches( &$matches ) {
570 $profile = new ProfileSection( __METHOD__
);
571 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
573 $out = "<ul class='mw-search-results'>\n";
574 $result = $matches->next();
576 while ( $result && $count < $this->limit
) {
577 $out .= $this->showHit( $result, $terms );
578 $result = $matches->next();
583 // convert the whole thing to desired language variant
584 $out = $wgContLang->convert( $out );
590 * Format a single hit result
592 * @param SearchResult $result
593 * @param array $terms Terms to highlight
597 protected function showHit( $result, $terms ) {
598 $profile = new ProfileSection( __METHOD__
);
600 if ( $result->isBrokenTitle() ) {
604 $title = $result->getTitle();
606 $titleSnippet = $result->getTitleSnippet( $terms );
608 if ( $titleSnippet == '' ) {
609 $titleSnippet = null;
612 $link_t = clone $title;
614 wfRunHooks( 'ShowSearchHitTitle',
615 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
617 $link = Linker
::linkKnown(
622 //If page content is not readable, just return the title.
623 //This is not quite safe, but better than showing excerpts from non-readable pages
624 //Note that hiding the entry entirely would screw up paging.
625 if ( !$title->userCan( 'read', $this->getUser() ) ) {
626 return "<li>{$link}</li>\n";
629 // If the page doesn't *exist*... our search index is out of date.
630 // The least confusing at this point is to drop the result.
631 // You may get less results, but... oh well. :P
632 if ( $result->isMissingRevision() ) {
636 // format redirects / relevant sections
637 $redirectTitle = $result->getRedirectTitle();
638 $redirectText = $result->getRedirectSnippet( $terms );
639 $sectionTitle = $result->getSectionTitle();
640 $sectionText = $result->getSectionSnippet( $terms );
643 if ( !is_null( $redirectTitle ) ) {
644 if ( $redirectText == '' ) {
645 $redirectText = null;
648 $redirect = "<span class='searchalttitle'>" .
649 $this->msg( 'search-redirect' )->rawParams(
650 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
656 if ( !is_null( $sectionTitle ) ) {
657 if ( $sectionText == '' ) {
661 $section = "<span class='searchalttitle'>" .
662 $this->msg( 'search-section' )->rawParams(
663 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
667 // format text extract
668 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
670 $lang = $this->getLanguage();
673 if ( is_null( $result->getScore() ) ) {
674 // Search engine doesn't report scoring info
677 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
678 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
682 // format description
683 $byteSize = $result->getByteSize();
684 $wordCount = $result->getWordCount();
685 $timestamp = $result->getTimestamp();
686 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
687 ->numParams( $wordCount )->escaped();
689 if ( $title->getNamespace() == NS_CATEGORY
) {
690 $cat = Category
::newFromTitle( $title );
691 $size = $this->msg( 'search-result-category-size' )
692 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
696 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
698 // link to related articles if supported
700 if ( $result->hasRelated() ) {
701 $stParams = array_merge(
702 $this->powerSearchOptions(),
704 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
705 ':' . $title->getPrefixedText(),
706 'fulltext' => $this->msg( 'search' )->text()
710 $related = ' -- ' . Linker
::linkKnown(
711 $this->getPageTitle(),
712 $this->msg( 'search-relatedarticle' )->text(),
719 // Include a thumbnail for media files...
720 if ( $title->getNamespace() == NS_FILE
) {
721 $img = $result->getFile();
722 $img = $img ?
: wfFindFile( $title );
723 if ( $result->isFileMatch() ) {
724 $fileMatch = "<span class='searchalttitle'>" .
725 $this->msg( 'search-file-match' )->escaped() . "</span>";
728 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
730 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
731 // Float doesn't seem to interact well with the bullets.
732 // Table messes up vertical alignment of the bullets.
733 // Bullets are therefore disabled (didn't look great anyway).
735 '<table class="searchResultImage">' .
737 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
738 $thumb->toHtml( array( 'desc-link' => true ) ) .
740 '<td style="vertical-align: top;">' .
741 "{$link} {$fileMatch}" .
743 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
754 if ( wfRunHooks( 'ShowSearchHit', array(
755 $this, $result, $terms,
756 &$link, &$redirect, &$section, &$extract,
757 &$score, &$size, &$date, &$related,
760 $html = "<li><div class='mw-search-result-heading'>" .
761 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
762 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
770 * Show results from other wikis
772 * @param SearchResultSet|array $matches
773 * @param string $query
777 protected function showInterwiki( $matches, $query ) {
779 $profile = new ProfileSection( __METHOD__
);
781 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
782 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
783 $out .= "<ul class='mw-search-iwresults'>\n";
785 // work out custom project captions
786 $customCaptions = array();
787 // format per line <iwprefix>:<caption>
788 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
789 foreach ( $customLines as $line ) {
790 $parts = explode( ":", $line, 2 );
791 if ( count( $parts ) == 2 ) { // validate line
792 $customCaptions[$parts[0]] = $parts[1];
796 if ( !is_array( $matches ) ) {
797 $matches = array( $matches );
800 foreach ( $matches as $set ) {
802 $result = $set->next();
804 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
805 $prev = $result->getInterwikiPrefix();
806 $result = $set->next();
810 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
811 $out .= "</ul></div>\n";
813 // convert the whole thing to desired language variant
814 $out = $wgContLang->convert( $out );
820 * Show single interwiki link
822 * @param SearchResult $result
823 * @param string $lastInterwiki
824 * @param string $query
825 * @param array $customCaptions iw prefix -> caption
829 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
830 $profile = new ProfileSection( __METHOD__
);
832 if ( $result->isBrokenTitle() ) {
836 $title = $result->getTitle();
838 $titleSnippet = $result->getTitleSnippet();
840 if ( $titleSnippet == '' ) {
841 $titleSnippet = null;
844 $link = Linker
::linkKnown(
849 // format redirect if any
850 $redirectTitle = $result->getRedirectTitle();
851 $redirectText = $result->getRedirectSnippet();
853 if ( !is_null( $redirectTitle ) ) {
854 if ( $redirectText == '' ) {
855 $redirectText = null;
858 $redirect = "<span class='searchalttitle'>" .
859 $this->msg( 'search-redirect' )->rawParams(
860 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
865 // display project name
866 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
867 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
868 // captions from 'search-interwiki-custom'
869 $caption = $customCaptions[$title->getInterwiki()];
871 // default is to show the hostname of the other wiki which might suck
872 // if there are many wikis on one hostname
873 $parsed = wfParseUrl( $title->getFullURL() );
874 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
876 // "more results" link (special page stuff could be localized, but we might not know target lang)
877 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
878 $searchLink = Linker
::linkKnown(
880 $this->msg( 'search-interwiki-more' )->text(),
884 'fulltext' => 'Search'
887 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
888 {$searchLink}</span>{$caption}</div>\n<ul>";
891 $out .= "<li>{$link} {$redirect}</li>\n";
897 * @param string $profile
898 * @param string $term
901 protected function getProfileForm( $profile, $term ) {
904 $opts['profile'] = $this->profile
;
906 if ( $profile === 'advanced' ) {
907 return $this->powerSearchBox( $term, $opts );
910 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
917 * Generates the power search box at [[Special:Search]]
919 * @param string $term Search term
921 * @return string HTML form
923 protected function powerSearchBox( $term, $opts ) {
926 // Groups namespaces into rows according to subject
928 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
929 $subject = MWNamespace
::getSubject( $namespace );
930 if ( !array_key_exists( $subject, $rows ) ) {
931 $rows[$subject] = "";
934 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
936 $name = $this->msg( 'blanknamespace' )->text();
941 'td', array( 'style' => 'white-space: nowrap' )
946 "mw-search-ns{$namespace}",
947 in_array( $namespace, $this->namespaces
)
949 Xml
::closeElement( 'td' );
952 $rows = array_values( $rows );
953 $numRows = count( $rows );
955 // Lays out namespaces in multiple floating two-column tables so they'll
956 // be arranged nicely while still accommodating different screen widths
957 $namespaceTables = '';
958 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
959 $namespaceTables .= Xml
::openElement(
961 array( 'cellpadding' => 0, 'cellspacing' => 0 )
964 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
965 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
968 $namespaceTables .= Xml
::closeElement( 'table' );
971 $showSections = array( 'namespaceTables' => $namespaceTables );
973 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
976 foreach ( $opts as $key => $value ) {
977 $hidden .= Html
::hidden( $key, $value );
980 # Stuff to feed saveNamespaces()
982 $user = $this->getUser();
983 if ( $user->isLoggedIn() ) {
984 $remember .= Html
::hidden( 'nsToken', $user->getEditToken() ) .
986 wfMessage( 'powersearch-remember' )->text(),
988 'mw-search-powersearch-remember',
993 // Return final output
994 return Xml
::openElement(
996 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
998 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
999 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1000 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
1001 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1002 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1004 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
1006 Xml
::closeElement( 'fieldset' );
1012 protected function getSearchProfiles() {
1013 // Builds list of Search Types (profiles)
1014 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1018 'message' => 'searchprofile-articles',
1019 'tooltip' => 'searchprofile-articles-tooltip',
1020 'namespaces' => SearchEngine
::defaultNamespaces(),
1021 'namespace-messages' => SearchEngine
::namespacesAsText(
1022 SearchEngine
::defaultNamespaces()
1026 'message' => 'searchprofile-images',
1027 'tooltip' => 'searchprofile-images-tooltip',
1028 'namespaces' => array( NS_FILE
),
1031 'message' => 'searchprofile-everything',
1032 'tooltip' => 'searchprofile-everything-tooltip',
1033 'namespaces' => $nsAllSet,
1035 'advanced' => array(
1036 'message' => 'searchprofile-advanced',
1037 'tooltip' => 'searchprofile-advanced-tooltip',
1038 'namespaces' => self
::NAMESPACES_CURRENT
,
1042 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1044 foreach ( $profiles as &$data ) {
1045 if ( !is_array( $data['namespaces'] ) ) {
1048 sort( $data['namespaces'] );
1055 * @param string $term
1056 * @param int $resultsShown
1057 * @param int $totalNum
1060 protected function formHeader( $term, $resultsShown, $totalNum ) {
1061 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1064 if ( $this->startsWithImage( $term ) ) {
1066 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1069 $profiles = $this->getSearchProfiles();
1070 $lang = $this->getLanguage();
1072 // Outputs XML for Search Types
1073 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1074 $out .= Xml
::openElement( 'ul' );
1075 foreach ( $profiles as $id => $profile ) {
1076 if ( !isset( $profile['parameters'] ) ) {
1077 $profile['parameters'] = array();
1079 $profile['parameters']['profile'] = $id;
1081 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1082 $lang->commaList( $profile['namespace-messages'] ) : null;
1086 'class' => $this->profile
=== $id ?
'current' : 'normal'
1088 $this->makeSearchLink(
1091 $this->msg( $profile['message'] )->text(),
1092 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1093 $profile['parameters']
1097 $out .= Xml
::closeElement( 'ul' );
1098 $out .= Xml
::closeElement( 'div' );
1101 if ( $resultsShown > 0 ) {
1102 if ( $totalNum > 0 ) {
1103 $top = $this->msg( 'showingresultsheader' )
1104 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1105 ->params( wfEscapeWikiText( $term ) )
1106 ->numParams( $resultsShown )
1108 } elseif ( $resultsShown >= $this->limit
) {
1109 $top = $this->msg( 'showingresults' )
1110 ->numParams( $this->limit
, $this->offset +
1 )
1113 $top = $this->msg( 'showingresultsnum' )
1114 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1117 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1118 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1122 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1123 $out .= Xml
::closeElement( 'div' );
1129 * @param string $term
1132 protected function shortDialog( $term ) {
1133 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1134 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1136 $out .= Html
::input( 'search', $term, 'search', array(
1137 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1140 'class' => 'mw-ui-input',
1142 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1143 $out .= Xml
::submitButton(
1144 $this->msg( 'searchbutton' )->text(),
1145 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1148 return $out . $this->didYouMeanHtml
;
1152 * Make a search link with some target namespaces
1154 * @param string $term
1155 * @param array $namespaces Ignored
1156 * @param string $label Link's text
1157 * @param string $tooltip Link's tooltip
1158 * @param array $params Query string parameters
1159 * @return string HTML fragment
1161 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1163 foreach ( $namespaces as $n ) {
1164 $opt['ns' . $n] = 1;
1167 $stParams = array_merge(
1170 'fulltext' => $this->msg( 'search' )->text()
1175 return Xml
::element(
1178 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1186 * Check if query starts with image: prefix
1188 * @param string $term The string to check
1191 protected function startsWithImage( $term ) {
1194 $parts = explode( ':', $term );
1195 if ( count( $parts ) > 1 ) {
1196 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1203 * Check if query starts with all: prefix
1205 * @param string $term The string to check
1208 protected function startsWithAll( $term ) {
1210 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1212 $parts = explode( ':', $term );
1213 if ( count( $parts ) > 1 ) {
1214 return $parts[0] == $allkeyword;
1223 * @return SearchEngine
1225 public function getSearchEngine() {
1226 if ( $this->searchEngine
=== null ) {
1227 $this->searchEngine
= $this->searchEngineType ?
1228 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1231 return $this->searchEngine
;
1235 * Current search profile.
1236 * @return null|string
1238 function getProfile() {
1239 return $this->profile
;
1243 * Current namespaces.
1246 function getNamespaces() {
1247 return $this->namespaces
;
1251 * Users of hook SpecialSearchSetupEngine can use this to
1252 * add more params to links to not lose selection when
1253 * user navigates search results.
1256 * @param string $key
1257 * @param mixed $value
1259 public function setExtraParam( $key, $value ) {
1260 $this->extraParams
[$key] = $value;
1263 protected function getGroupName() {