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 $textMatches = $search->searchText( $rewritten );
259 if ( $textMatches instanceof Status
) {
260 $textStatus = $textMatches;
264 // did you mean... suggestions
265 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
266 # mirror Go/Search behavior of original request ..
267 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
269 if ( $this->fulltext
!= null ) {
270 $didYouMeanParams['fulltext'] = $this->fulltext
;
273 $stParams = array_merge(
275 $this->powerSearchOptions()
278 $suggestionSnippet = $textMatches->getSuggestionSnippet();
280 if ( $suggestionSnippet == '' ) {
281 $suggestionSnippet = null;
284 $suggestLink = Linker
::linkKnown(
285 $this->getPageTitle(),
291 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
292 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
295 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
296 # Hook requested termination
300 // start rendering the page
305 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
307 'action' => $wgScript
312 # This is an awful awful ID name. It's not a table, but we
313 # named it poorly from when this was a table so now we're
315 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
316 $this->shortDialog( $term ) .
317 Xml
::closeElement( 'div' )
320 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
321 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
322 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
323 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
324 $out->addHTML( '</form>' );
326 // Empty query -- straight view of search form
330 // Get number of results
331 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
332 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
333 // Total initial query matches (possible false positives)
334 $num = $titleMatchesNum +
$textMatchesNum;
336 // Get total actual results (after second filtering, if any)
337 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
338 $titleMatches->getTotalHits() : $titleMatchesNum;
339 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
340 $textMatches->getTotalHits() : $textMatchesNum;
342 // get total number of results if backend can calculate it
344 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
345 $totalRes +
= $titleMatches->getTotalHits();
347 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
348 $totalRes +
= $textMatches->getTotalHits();
351 // show number of results and current offset
352 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
353 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
355 $out->addHtml( Xml
::closeElement( 'form' ) );
356 $out->addHtml( "<div class='searchresults'>" );
360 if ( $num ||
$this->offset
) {
361 // Show the create link ahead
362 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
363 if ( $totalRes > $this->limit ||
$this->offset
) {
364 $prevnext = $this->getLanguage()->viewPrevNext(
365 $this->getPageTitle(),
368 $this->powerSearchOptions() +
array( 'search' => $term ),
369 max( $titleMatchesNum, $textMatchesNum ) <= $this->limit
372 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
374 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
377 $out->parserOptions()->setEditSection( false );
378 if ( $titleMatches ) {
379 if ( $numTitleMatches > 0 ) {
380 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
381 $out->addHTML( $this->showMatches( $titleMatches ) );
383 $titleMatches->free();
385 if ( $textMatches && !$textStatus ) {
386 // output appropriate heading
387 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
388 // if no title matches the heading is redundant
389 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
392 // show interwiki results if any
393 if ( $textMatches->hasInterwikiResults() ) {
394 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
397 if ( $numTextMatches > 0 ) {
398 $out->addHTML( $this->showMatches( $textMatches ) );
401 $textMatches->free();
405 $out->addHTML( '<div class="error">' .
406 $textStatus->getMessage( 'search-error' ) . '</div>' );
408 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
409 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
410 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
413 $out->addHtml( "</div>" );
416 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
421 * @param Title $title
422 * @param int $num The number of search results found
423 * @param null|SearchResultSet $titleMatches Results from title search
424 * @param null|SearchResultSet $textMatches Results from text search
426 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
427 // show direct page/create link if applicable
429 // Check DBkey !== '' in case of fragment link only.
430 if ( is_null( $title ) ||
$title->getDBkey() === ''
431 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
432 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
435 // preserve the paragraph for margins etc...
436 $this->getOutput()->addHtml( '<p></p>' );
441 if ( $title->isKnown() ) {
442 $messageName = 'searchmenu-exists';
443 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
444 $messageName = 'searchmenu-new';
446 $messageName = 'searchmenu-new-nocreate';
450 wfEscapeWikiText( $title->getPrefixedText() ),
451 Message
::numParam( $num )
453 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
455 // Extensions using the hook might still return an empty $messageName
456 if ( $messageName ) {
457 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
459 // preserve the paragraph for margins etc...
460 $this->getOutput()->addHtml( '<p></p>' );
465 * @param string $term
467 protected function setupPage( $term ) {
468 # Should advanced UI be used?
469 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
470 $out = $this->getOutput();
471 if ( strval( $term ) !== '' ) {
472 $out->setPageTitle( $this->msg( 'searchresults' ) );
473 $out->setHTMLTitle( $this->msg( 'pagetitle' )
474 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
475 ->inContentLanguage()->text()
478 // add javascript specific to special:search
479 $out->addModules( 'mediawiki.special.search' );
483 * Extract "power search" namespace settings from the request object,
484 * returning a list of index numbers to search.
486 * @param WebRequest $request
489 protected function powerSearch( &$request ) {
491 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
492 if ( $request->getCheck( 'ns' . $ns ) ) {
501 * Reconstruct the 'power search' options for links
505 protected function powerSearchOptions() {
507 if ( $this->profile
!== 'advanced' ) {
508 $opt['profile'] = $this->profile
;
510 foreach ( $this->namespaces
as $n ) {
515 return $opt +
$this->extraParams
;
519 * Save namespace preferences when we're supposed to
521 * @return bool Whether we wrote something
523 protected function saveNamespaces() {
524 $user = $this->getUser();
525 $request = $this->getRequest();
527 if ( $user->isLoggedIn() &&
528 !is_null( $request->getVal( 'nsRemember' ) ) &&
529 $user->matchEditToken( $request->getVal( 'nsToken' ) )
531 // Reset namespace preferences: namespaces are not searched
532 // when they're not mentioned in the URL parameters.
533 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
534 $user->setOption( 'searchNs' . $n, false );
536 // The request parameters include all the namespaces we just searched.
537 // Even if they're the same as an existing profile, they're not eaten.
538 foreach ( $this->namespaces
as $n ) {
539 $user->setOption( 'searchNs' . $n, true );
542 $user->saveSettings();
550 * Show whole set of results
552 * @param SearchResultSet $matches
556 protected function showMatches( &$matches ) {
559 $profile = new ProfileSection( __METHOD__
);
560 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
562 $out = "<ul class='mw-search-results'>\n";
563 $result = $matches->next();
565 while ( $result && $count < $this->limit
) {
566 $out .= $this->showHit( $result, $terms );
567 $result = $matches->next();
572 // convert the whole thing to desired language variant
573 $out = $wgContLang->convert( $out );
579 * Format a single hit result
581 * @param SearchResult $result
582 * @param array $terms Terms to highlight
586 protected function showHit( $result, $terms ) {
587 $profile = new ProfileSection( __METHOD__
);
589 if ( $result->isBrokenTitle() ) {
593 $title = $result->getTitle();
595 $titleSnippet = $result->getTitleSnippet( $terms );
597 if ( $titleSnippet == '' ) {
598 $titleSnippet = null;
601 $link_t = clone $title;
603 wfRunHooks( 'ShowSearchHitTitle',
604 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
606 $link = Linker
::linkKnown(
611 //If page content is not readable, just return the title.
612 //This is not quite safe, but better than showing excerpts from non-readable pages
613 //Note that hiding the entry entirely would screw up paging.
614 if ( !$title->userCan( 'read', $this->getUser() ) ) {
615 return "<li>{$link}</li>\n";
618 // If the page doesn't *exist*... our search index is out of date.
619 // The least confusing at this point is to drop the result.
620 // You may get less results, but... oh well. :P
621 if ( $result->isMissingRevision() ) {
625 // format redirects / relevant sections
626 $redirectTitle = $result->getRedirectTitle();
627 $redirectText = $result->getRedirectSnippet( $terms );
628 $sectionTitle = $result->getSectionTitle();
629 $sectionText = $result->getSectionSnippet( $terms );
632 if ( !is_null( $redirectTitle ) ) {
633 if ( $redirectText == '' ) {
634 $redirectText = null;
637 $redirect = "<span class='searchalttitle'>" .
638 $this->msg( 'search-redirect' )->rawParams(
639 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
645 if ( !is_null( $sectionTitle ) ) {
646 if ( $sectionText == '' ) {
650 $section = "<span class='searchalttitle'>" .
651 $this->msg( 'search-section' )->rawParams(
652 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
656 // format text extract
657 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
659 $lang = $this->getLanguage();
662 if ( is_null( $result->getScore() ) ) {
663 // Search engine doesn't report scoring info
666 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
667 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
671 // format description
672 $byteSize = $result->getByteSize();
673 $wordCount = $result->getWordCount();
674 $timestamp = $result->getTimestamp();
675 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
676 ->numParams( $wordCount )->escaped();
678 if ( $title->getNamespace() == NS_CATEGORY
) {
679 $cat = Category
::newFromTitle( $title );
680 $size = $this->msg( 'search-result-category-size' )
681 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
685 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
687 // link to related articles if supported
689 if ( $result->hasRelated() ) {
690 $stParams = array_merge(
691 $this->powerSearchOptions(),
693 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
694 ':' . $title->getPrefixedText(),
695 'fulltext' => $this->msg( 'search' )->text()
699 $related = ' -- ' . Linker
::linkKnown(
700 $this->getPageTitle(),
701 $this->msg( 'search-relatedarticle' )->text(),
708 // Include a thumbnail for media files...
709 if ( $title->getNamespace() == NS_FILE
) {
710 $img = $result->getFile();
711 $img = $img ?
: wfFindFile( $title );
712 if ( $result->isFileMatch() ) {
713 $fileMatch = "<span class='searchalttitle'>" .
714 $this->msg( 'search-file-match' )->escaped() . "</span>";
717 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
719 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
720 // Float doesn't seem to interact well with the bullets.
721 // Table messes up vertical alignment of the bullets.
722 // Bullets are therefore disabled (didn't look great anyway).
724 '<table class="searchResultImage">' .
726 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
727 $thumb->toHtml( array( 'desc-link' => true ) ) .
729 '<td style="vertical-align: top;">' .
730 "{$link} {$fileMatch}" .
732 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
743 if ( wfRunHooks( 'ShowSearchHit', array(
744 $this, $result, $terms,
745 &$link, &$redirect, &$section, &$extract,
746 &$score, &$size, &$date, &$related,
749 $html = "<li><div class='mw-search-result-heading'>" .
750 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
751 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
759 * Show results from other wikis
761 * @param SearchResultSet|array $matches
762 * @param string $query
766 protected function showInterwiki( $matches, $query ) {
768 $profile = new ProfileSection( __METHOD__
);
770 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
771 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
772 $out .= "<ul class='mw-search-iwresults'>\n";
774 // work out custom project captions
775 $customCaptions = array();
776 // format per line <iwprefix>:<caption>
777 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
778 foreach ( $customLines as $line ) {
779 $parts = explode( ":", $line, 2 );
780 if ( count( $parts ) == 2 ) { // validate line
781 $customCaptions[$parts[0]] = $parts[1];
785 if ( !is_array( $matches ) ) {
786 $matches = array( $matches );
789 foreach ( $matches as $set ) {
791 $result = $set->next();
793 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
794 $prev = $result->getInterwikiPrefix();
795 $result = $set->next();
799 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
800 $out .= "</ul></div>\n";
802 // convert the whole thing to desired language variant
803 $out = $wgContLang->convert( $out );
809 * Show single interwiki link
811 * @param SearchResult $result
812 * @param string $lastInterwiki
813 * @param string $query
814 * @param array $customCaptions iw prefix -> caption
818 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
819 $profile = new ProfileSection( __METHOD__
);
821 if ( $result->isBrokenTitle() ) {
825 $title = $result->getTitle();
827 $titleSnippet = $result->getTitleSnippet();
829 if ( $titleSnippet == '' ) {
830 $titleSnippet = null;
833 $link = Linker
::linkKnown(
838 // format redirect if any
839 $redirectTitle = $result->getRedirectTitle();
840 $redirectText = $result->getRedirectSnippet();
842 if ( !is_null( $redirectTitle ) ) {
843 if ( $redirectText == '' ) {
844 $redirectText = null;
847 $redirect = "<span class='searchalttitle'>" .
848 $this->msg( 'search-redirect' )->rawParams(
849 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
854 // display project name
855 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
856 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
857 // captions from 'search-interwiki-custom'
858 $caption = $customCaptions[$title->getInterwiki()];
860 // default is to show the hostname of the other wiki which might suck
861 // if there are many wikis on one hostname
862 $parsed = wfParseUrl( $title->getFullURL() );
863 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
865 // "more results" link (special page stuff could be localized, but we might not know target lang)
866 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
867 $searchLink = Linker
::linkKnown(
869 $this->msg( 'search-interwiki-more' )->text(),
873 'fulltext' => 'Search'
876 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
877 {$searchLink}</span>{$caption}</div>\n<ul>";
880 $out .= "<li>{$link} {$redirect}</li>\n";
886 * @param string $profile
887 * @param string $term
890 protected function getProfileForm( $profile, $term ) {
893 $opts['profile'] = $this->profile
;
895 if ( $profile === 'advanced' ) {
896 return $this->powerSearchBox( $term, $opts );
899 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
906 * Generates the power search box at [[Special:Search]]
908 * @param string $term Search term
910 * @return string HTML form
912 protected function powerSearchBox( $term, $opts ) {
915 // Groups namespaces into rows according to subject
917 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
918 $subject = MWNamespace
::getSubject( $namespace );
919 if ( !array_key_exists( $subject, $rows ) ) {
920 $rows[$subject] = "";
923 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
925 $name = $this->msg( 'blanknamespace' )->text();
930 'td', array( 'style' => 'white-space: nowrap' )
935 "mw-search-ns{$namespace}",
936 in_array( $namespace, $this->namespaces
)
938 Xml
::closeElement( 'td' );
941 $rows = array_values( $rows );
942 $numRows = count( $rows );
944 // Lays out namespaces in multiple floating two-column tables so they'll
945 // be arranged nicely while still accommodating different screen widths
946 $namespaceTables = '';
947 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
948 $namespaceTables .= Xml
::openElement(
950 array( 'cellpadding' => 0, 'cellspacing' => 0 )
953 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
954 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
957 $namespaceTables .= Xml
::closeElement( 'table' );
960 $showSections = array( 'namespaceTables' => $namespaceTables );
962 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
965 foreach ( $opts as $key => $value ) {
966 $hidden .= Html
::hidden( $key, $value );
969 # Stuff to feed saveNamespaces()
971 $user = $this->getUser();
972 if ( $user->isLoggedIn() ) {
973 $remember .= Html
::hidden( 'nsToken', $user->getEditToken() ) .
975 wfMessage( 'powersearch-remember' )->text(),
977 'mw-search-powersearch-remember',
982 // Return final output
983 return Xml
::openElement(
985 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
987 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
988 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
989 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
990 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
991 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
993 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
995 Xml
::closeElement( 'fieldset' );
1001 protected function getSearchProfiles() {
1002 // Builds list of Search Types (profiles)
1003 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
1007 'message' => 'searchprofile-articles',
1008 'tooltip' => 'searchprofile-articles-tooltip',
1009 'namespaces' => SearchEngine
::defaultNamespaces(),
1010 'namespace-messages' => SearchEngine
::namespacesAsText(
1011 SearchEngine
::defaultNamespaces()
1015 'message' => 'searchprofile-images',
1016 'tooltip' => 'searchprofile-images-tooltip',
1017 'namespaces' => array( NS_FILE
),
1020 'message' => 'searchprofile-everything',
1021 'tooltip' => 'searchprofile-everything-tooltip',
1022 'namespaces' => $nsAllSet,
1024 'advanced' => array(
1025 'message' => 'searchprofile-advanced',
1026 'tooltip' => 'searchprofile-advanced-tooltip',
1027 'namespaces' => self
::NAMESPACES_CURRENT
,
1031 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1033 foreach ( $profiles as &$data ) {
1034 if ( !is_array( $data['namespaces'] ) ) {
1037 sort( $data['namespaces'] );
1044 * @param string $term
1045 * @param int $resultsShown
1046 * @param int $totalNum
1049 protected function formHeader( $term, $resultsShown, $totalNum ) {
1050 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1053 if ( $this->startsWithImage( $term ) ) {
1055 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1058 $profiles = $this->getSearchProfiles();
1059 $lang = $this->getLanguage();
1061 // Outputs XML for Search Types
1062 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1063 $out .= Xml
::openElement( 'ul' );
1064 foreach ( $profiles as $id => $profile ) {
1065 if ( !isset( $profile['parameters'] ) ) {
1066 $profile['parameters'] = array();
1068 $profile['parameters']['profile'] = $id;
1070 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1071 $lang->commaList( $profile['namespace-messages'] ) : null;
1075 'class' => $this->profile
=== $id ?
'current' : 'normal'
1077 $this->makeSearchLink(
1080 $this->msg( $profile['message'] )->text(),
1081 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1082 $profile['parameters']
1086 $out .= Xml
::closeElement( 'ul' );
1087 $out .= Xml
::closeElement( 'div' );
1090 if ( $resultsShown > 0 ) {
1091 if ( $totalNum > 0 ) {
1092 $top = $this->msg( 'showingresultsheader' )
1093 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1094 ->params( wfEscapeWikiText( $term ) )
1095 ->numParams( $resultsShown )
1097 } elseif ( $resultsShown >= $this->limit
) {
1098 $top = $this->msg( 'showingresults' )
1099 ->numParams( $this->limit
, $this->offset +
1 )
1102 $top = $this->msg( 'showingresultsnum' )
1103 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1106 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1107 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1111 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1112 $out .= Xml
::closeElement( 'div' );
1118 * @param string $term
1121 protected function shortDialog( $term ) {
1122 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1123 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1125 $out .= Html
::input( 'search', $term, 'search', array(
1126 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1129 'class' => 'mw-ui-input',
1131 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1132 $out .= Xml
::submitButton(
1133 $this->msg( 'searchbutton' )->text(),
1134 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1137 return $out . $this->didYouMeanHtml
;
1141 * Make a search link with some target namespaces
1143 * @param string $term
1144 * @param array $namespaces Ignored
1145 * @param string $label Link's text
1146 * @param string $tooltip Link's tooltip
1147 * @param array $params Query string parameters
1148 * @return string HTML fragment
1150 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1152 foreach ( $namespaces as $n ) {
1153 $opt['ns' . $n] = 1;
1156 $stParams = array_merge(
1159 'fulltext' => $this->msg( 'search' )->text()
1164 return Xml
::element(
1167 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1175 * Check if query starts with image: prefix
1177 * @param string $term The string to check
1180 protected function startsWithImage( $term ) {
1183 $parts = explode( ':', $term );
1184 if ( count( $parts ) > 1 ) {
1185 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1192 * Check if query starts with all: prefix
1194 * @param string $term The string to check
1197 protected function startsWithAll( $term ) {
1199 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1201 $parts = explode( ':', $term );
1202 if ( count( $parts ) > 1 ) {
1203 return $parts[0] == $allkeyword;
1212 * @return SearchEngine
1214 public function getSearchEngine() {
1215 if ( $this->searchEngine
=== null ) {
1216 $this->searchEngine
= $this->searchEngineType ?
1217 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1220 return $this->searchEngine
;
1224 * Current search profile.
1225 * @return null|string
1227 function getProfile() {
1228 return $this->profile
;
1232 * Current namespaces.
1235 function getNamespaces() {
1236 return $this->namespaces
;
1240 * Users of hook SpecialSearchSetupEngine can use this to
1241 * add more params to links to not lose selection when
1242 * user navigates search results.
1245 * @param string $key
1246 * @param mixed $value
1248 public function setExtraParam( $key, $value ) {
1249 $this->extraParams
[$key] = $value;
1252 protected function getGroupName() {