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, help, 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.
40 function getProfile() { return $this->profile
; }
43 protected $searchEngine;
46 protected $extraParams = array();
48 /// No idea, apparently used by some other classes
54 protected $limit, $offset;
59 protected $namespaces;
60 function getNamespaces() { return $this->namespaces
; }
65 protected $searchRedirects;
70 protected $didYouMeanHtml, $fulltext;
72 const NAMESPACES_CURRENT
= 'sense';
74 public function __construct() {
75 parent
::__construct( 'Search' );
81 * @param $par String or null
83 public function execute( $par ) {
85 $this->outputHeader();
86 $out = $this->getOutput();
87 $out->allowClickjacking();
88 $out->addModuleStyles( 'mediawiki.special' );
90 // Strip underscores from title parameter; most of the time we'll want
91 // text form here. But don't strip underscores from actual text params!
92 $titleParam = str_replace( '_', ' ', $par );
94 $request = $this->getRequest();
96 // Fetch the search term
97 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
101 if ( $request->getVal( 'fulltext' )
102 ||
!is_null( $request->getVal( 'offset' ) )
103 ||
!is_null( $request->getVal( 'searchx' ) ) )
105 $this->showResults( $search );
107 $this->goResult( $search );
112 * Set up basic search parameters from the request and user settings.
114 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
116 public function load() {
117 $request = $this->getRequest();
118 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, 'searchlimit' );
119 $this->mPrefix
= $request->getVal( 'prefix', '' );
121 $user = $this->getUser();
123 # Extract manually requested namespaces
124 $nslist = $this->powerSearch( $request );
125 if ( !count( $nslist ) ) {
126 # Fallback to user preference
127 $nslist = SearchEngine
::userNamespaces( $user );
131 if ( !count( $nslist ) ) {
132 $profile = 'default';
135 $profile = $request->getVal( 'profile', $profile );
136 $profiles = $this->getSearchProfiles();
137 if ( $profile === null ) {
138 // BC with old request format
139 $profile = 'advanced';
140 foreach( $profiles as $key => $data ) {
141 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
145 $this->namespaces
= $nslist;
146 } elseif ( $profile === 'advanced' ) {
147 $this->namespaces
= $nslist;
149 if ( isset( $profiles[$profile]['namespaces'] ) ) {
150 $this->namespaces
= $profiles[$profile]['namespaces'];
152 // Unknown profile requested
153 $profile = 'default';
154 $this->namespaces
= $profiles['default']['namespaces'];
158 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
159 $default = $request->getBool( 'profile' ) ?
0 : 1;
160 $this->searchRedirects
= $request->getBool( 'redirs', $default ) ?
1 : 0;
161 $this->didYouMeanHtml
= ''; # html of did you mean... link
162 $this->fulltext
= $request->getVal( 'fulltext' );
163 $this->profile
= $profile;
167 * If an exact title match can be found, jump straight ahead to it.
169 * @param $term String
171 public function goResult( $term ) {
172 $this->setupPage( $term );
173 # Try to go to page as entered.
174 $t = Title
::newFromText( $term );
175 # If the string cannot be used to create a title
176 if( is_null( $t ) ) {
177 $this->showResults( $term );
180 # If there's an exact or very near match, jump right there.
181 $t = SearchEngine
::getNearMatch( $term );
183 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
184 # Hook requested termination
188 if( !is_null( $t ) ) {
189 $this->getOutput()->redirect( $t->getFullURL() );
192 # No match, generate an edit URL
193 $t = Title
::newFromText( $term );
194 if( !is_null( $t ) ) {
196 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
197 wfDebugLog( 'nogomatch', $t->getText(), false );
199 # If the feature is enabled, go straight to the edit page
201 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
205 $this->showResults( $term );
209 * @param $term String
211 public function showResults( $term ) {
212 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
213 wfProfileIn( __METHOD__
);
215 $search = $this->getSearchEngine();
216 $search->setLimitOffset( $this->limit
, $this->offset
);
217 $search->setNamespaces( $this->namespaces
);
218 $search->showRedirects
= $this->searchRedirects
; // BC
219 $search->setFeatureData( 'list-redirects', $this->searchRedirects
);
220 $search->prefix
= $this->mPrefix
;
221 $term = $search->transformSearchTerm( $term );
223 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
225 $this->setupPage( $term );
227 $out = $this->getOutput();
229 if ( $wgDisableTextSearch ) {
230 if ( $wgSearchForwardUrl ) {
231 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
232 $out->redirect( $url );
235 Xml
::openElement( 'fieldset' ) .
236 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
237 Xml
::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
238 $this->msg( 'googlesearch' )->rawParams(
239 htmlspecialchars( $term ),
241 $this->msg( 'searchbutton' )->escaped()
243 Xml
::closeElement( 'fieldset' )
246 wfProfileOut( __METHOD__
);
250 $t = Title
::newFromText( $term );
252 // fetch search results
253 $rewritten = $search->replacePrefixes( $term );
255 $titleMatches = $search->searchTitle( $rewritten );
256 if( !( $titleMatches instanceof SearchResultTooMany
) ) {
257 $textMatches = $search->searchText( $rewritten );
260 // did you mean... suggestions
261 if( $textMatches && $textMatches->hasSuggestion() ) {
262 $st = SpecialPage
::getTitleFor( 'Search' );
264 # mirror Go/Search behaviour of original request ..
265 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
267 if( $this->fulltext
!= null ) {
268 $didYouMeanParams['fulltext'] = $this->fulltext
;
271 $stParams = array_merge(
273 $this->powerSearchOptions()
276 $suggestionSnippet = $textMatches->getSuggestionSnippet();
278 if( $suggestionSnippet == '' ) {
279 $suggestionSnippet = null;
282 $suggestLink = Linker
::linkKnown(
289 $this->didYouMeanHtml
= '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
292 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
293 # Hook requested termination
294 wfProfileOut( __METHOD__
);
298 // start rendering the page
303 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
305 'action' => $wgScript
310 Xml
::openElement( 'table', array( 'id' => 'mw-search-top-table', 'cellpadding' => 0, 'cellspacing' => 0 ) ) .
311 Xml
::openElement( 'tr' ) .
312 Xml
::openElement( 'td' ) . "\n" .
313 $this->shortDialog( $term ) .
314 Xml
::closeElement( 'td' ) .
315 Xml
::closeElement( 'tr' ) .
316 Xml
::closeElement( 'table' )
319 // Sometimes the search engine knows there are too many hits
320 if( $titleMatches instanceof SearchResultTooMany
) {
321 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
322 wfProfileOut( __METHOD__
);
326 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
327 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
328 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
329 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
330 $out->addHTML( '</form>' );
331 // Empty query -- straight view of search form
332 wfProfileOut( __METHOD__
);
336 // Get number of results
337 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
338 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
339 // Total initial query matches (possible false positives)
340 $num = $titleMatchesNum +
$textMatchesNum;
342 // Get total actual results (after second filtering, if any)
343 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
344 $titleMatches->getTotalHits() : $titleMatchesNum;
345 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
346 $textMatches->getTotalHits() : $textMatchesNum;
348 // get total number of results if backend can calculate it
350 if( $titleMatches && !is_null( $titleMatches->getTotalHits() ) )
351 $totalRes +
= $titleMatches->getTotalHits();
352 if( $textMatches && !is_null( $textMatches->getTotalHits() ) )
353 $totalRes +
= $textMatches->getTotalHits();
355 // show number of results and current offset
356 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
357 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
360 $out->addHtml( Xml
::closeElement( 'form' ) );
361 $out->addHtml( "<div class='searchresults'>" );
364 if( $num ||
$this->offset
) {
365 // Show the create link ahead
366 $this->showCreateLink( $t );
367 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
368 $this->powerSearchOptions() +
array( 'search' => $term ),
369 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
371 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
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();
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' );
390 } elseif( $totalRes == 0 ) {
391 # Don't show the 'no text matches' if we received title matches
392 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
394 // show interwiki results if any
395 if( $textMatches->hasInterwikiResults() ) {
396 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
399 if( $numTextMatches > 0 ) {
400 $out->addHTML( $this->showMatches( $textMatches ) );
403 $textMatches->free();
406 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
407 $this->showCreateLink( $t );
409 $out->addHtml( "</div>" );
411 if( $num ||
$this->offset
) {
412 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
414 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
415 wfProfileOut( __METHOD__
);
421 protected function showCreateLink( $t ) {
422 // show direct page/create link if applicable
424 // Check DBkey !== '' in case of fragment link only.
425 if( is_null( $t ) ||
$t->getDBkey() === '' ) {
427 // preserve the paragraph for margins etc...
428 $this->getOutput()->addHtml( '<p></p>' );
432 if( $t->isKnown() ) {
433 $messageName = 'searchmenu-exists';
434 } elseif( $t->userCan( 'create', $this->getUser() ) ) {
435 $messageName = 'searchmenu-new';
437 $messageName = 'searchmenu-new-nocreate';
439 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
440 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
442 // Extensions using the hook might still return an empty $messageName
444 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
446 // preserve the paragraph for margins etc...
447 $this->getOutput()->addHtml( '<p></p>' );
452 * @param $term string
454 protected function setupPage( $term ) {
455 # Should advanced UI be used?
456 $this->searchAdvanced
= ($this->profile
=== 'advanced');
457 $out = $this->getOutput();
458 if( strval( $term ) !== '' ) {
459 $out->setPageTitle( $this->msg( 'searchresults' ) );
460 $out->setHTMLTitle( $this->msg( 'pagetitle' )->rawParams(
461 $this->msg( 'searchresults-title' )->rawParams( $term )->text()
464 // add javascript specific to special:search
465 $out->addModules( 'mediawiki.special.search' );
469 * Extract "power search" namespace settings from the request object,
470 * returning a list of index numbers to search.
472 * @param $request WebRequest
475 protected function powerSearch( &$request ) {
477 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
478 if( $request->getCheck( 'ns' . $ns ) ) {
487 * Reconstruct the 'power search' options for links
491 protected function powerSearchOptions() {
493 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
494 if( $this->profile
!== 'advanced' ) {
495 $opt['profile'] = $this->profile
;
497 foreach( $this->namespaces
as $n ) {
501 return $opt +
$this->extraParams
;
505 * Show whole set of results
507 * @param $matches SearchResultSet
511 protected function showMatches( &$matches ) {
513 wfProfileIn( __METHOD__
);
515 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
518 $infoLine = $matches->getInfo();
519 if( !is_null( $infoLine ) ) {
520 $out .= "\n<!-- {$infoLine} -->\n";
522 $out .= "<ul class='mw-search-results'>\n";
523 $result = $matches->next();
525 $out .= $this->showHit( $result, $terms );
526 $result = $matches->next();
530 // convert the whole thing to desired language variant
531 $out = $wgContLang->convert( $out );
532 wfProfileOut( __METHOD__
);
537 * Format a single hit result
539 * @param $result SearchResult
540 * @param $terms Array: terms to highlight
544 protected function showHit( $result, $terms ) {
545 wfProfileIn( __METHOD__
);
547 if( $result->isBrokenTitle() ) {
548 wfProfileOut( __METHOD__
);
549 return "<!-- Broken link in search result -->\n";
552 $t = $result->getTitle();
554 $titleSnippet = $result->getTitleSnippet( $terms );
556 if( $titleSnippet == '' )
557 $titleSnippet = null;
561 wfRunHooks( 'ShowSearchHitTitle',
562 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
564 $link = Linker
::linkKnown(
569 //If page content is not readable, just return the title.
570 //This is not quite safe, but better than showing excerpts from non-readable pages
571 //Note that hiding the entry entirely would screw up paging.
572 if( !$t->userCan( 'read', $this->getUser() ) ) {
573 wfProfileOut( __METHOD__
);
574 return "<li>{$link}</li>\n";
577 // If the page doesn't *exist*... our search index is out of date.
578 // The least confusing at this point is to drop the result.
579 // You may get less results, but... oh well. :P
580 if( $result->isMissingRevision() ) {
581 wfProfileOut( __METHOD__
);
582 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
585 // format redirects / relevant sections
586 $redirectTitle = $result->getRedirectTitle();
587 $redirectText = $result->getRedirectSnippet( $terms );
588 $sectionTitle = $result->getSectionTitle();
589 $sectionText = $result->getSectionSnippet( $terms );
592 if( !is_null( $redirectTitle ) ) {
593 if( $redirectText == '' )
594 $redirectText = null;
596 $redirect = "<span class='searchalttitle'>" .
597 $this->msg( 'search-redirect' )->rawParams(
598 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
604 if( !is_null( $sectionTitle ) ) {
605 if( $sectionText == '' )
608 $section = "<span class='searchalttitle'>" .
609 $this->msg( 'search-section' )->rawParams(
610 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
614 // format text extract
615 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
617 $lang = $this->getLanguage();
620 if( is_null( $result->getScore() ) ) {
621 // Search engine doesn't report scoring info
624 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
625 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
629 // format description
630 $byteSize = $result->getByteSize();
631 $wordCount = $result->getWordCount();
632 $timestamp = $result->getTimestamp();
633 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
634 ->numParams( $wordCount )->escaped();
636 if( $t->getNamespace() == NS_CATEGORY
) {
637 $cat = Category
::newFromTitle( $t );
638 $size = $this->msg( 'search-result-category-size' )
639 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
643 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
645 // link to related articles if supported
647 if( $result->hasRelated() ) {
648 $st = SpecialPage
::getTitleFor( 'Search' );
649 $stParams = array_merge(
650 $this->powerSearchOptions(),
652 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
653 ':' . $t->getPrefixedText(),
654 'fulltext' => $this->msg( 'search' )->text()
658 $related = ' -- ' . Linker
::linkKnown(
660 $this->msg( 'search-relatedarticle' )->text(),
666 // Include a thumbnail for media files...
667 if( $t->getNamespace() == NS_FILE
) {
668 $img = wfFindFile( $t );
670 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
672 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
673 wfProfileOut( __METHOD__
);
674 // Float doesn't seem to interact well with the bullets.
675 // Table messes up vertical alignment of the bullets.
676 // Bullets are therefore disabled (didn't look great anyway).
678 '<table class="searchResultImage">' .
680 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
681 $thumb->toHtml( array( 'desc-link' => true ) ) .
683 '<td style="vertical-align: top;">' .
686 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
697 if ( wfRunHooks( 'ShowSearchHit', array (
698 $this, $result, $terms,
699 &$link, &$redirect, &$section, &$extract,
700 &$score, &$size, &$date, &$related,
703 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
704 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
708 wfProfileOut( __METHOD__
);
713 * Show results from other wikis
715 * @param $matches SearchResultSet
716 * @param $query String
720 protected function showInterwiki( &$matches, $query ) {
722 wfProfileIn( __METHOD__
);
723 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
725 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
726 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
727 $out .= "<ul class='mw-search-iwresults'>\n";
729 // work out custom project captions
730 $customCaptions = array();
731 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
732 foreach( $customLines as $line ) {
733 $parts = explode( ":", $line, 2 );
734 if( count( $parts ) == 2 ) { // validate line
735 $customCaptions[$parts[0]] = $parts[1];
740 $result = $matches->next();
742 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
743 $prev = $result->getInterwikiPrefix();
744 $result = $matches->next();
746 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
747 $out .= "</ul></div>\n";
749 // convert the whole thing to desired language variant
750 $out = $wgContLang->convert( $out );
751 wfProfileOut( __METHOD__
);
756 * Show single interwiki link
758 * @param $result SearchResult
759 * @param $lastInterwiki String
760 * @param $terms Array
761 * @param $query String
762 * @param $customCaptions Array: iw prefix -> caption
766 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
767 wfProfileIn( __METHOD__
);
769 if( $result->isBrokenTitle() ) {
770 wfProfileOut( __METHOD__
);
771 return "<!-- Broken link in search result -->\n";
774 $t = $result->getTitle();
776 $titleSnippet = $result->getTitleSnippet( $terms );
778 if( $titleSnippet == '' )
779 $titleSnippet = null;
781 $link = Linker
::linkKnown(
786 // format redirect if any
787 $redirectTitle = $result->getRedirectTitle();
788 $redirectText = $result->getRedirectSnippet( $terms );
790 if( !is_null( $redirectTitle ) ) {
791 if( $redirectText == '' )
792 $redirectText = null;
794 $redirect = "<span class='searchalttitle'>" .
795 $this->msg( 'search-redirect' )->rawParams(
796 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
801 // display project name
802 if( is_null( $lastInterwiki ) ||
$lastInterwiki != $t->getInterwiki() ) {
803 if( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
804 // captions from 'search-interwiki-custom'
805 $caption = $customCaptions[$t->getInterwiki()];
807 // default is to show the hostname of the other wiki which might suck
808 // if there are many wikis on one hostname
809 $parsed = wfParseUrl( $t->getFullURL() );
810 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
812 // "more results" link (special page stuff could be localized, but we might not know target lang)
813 $searchTitle = Title
::newFromText( $t->getInterwiki() . ":Special:Search" );
814 $searchLink = Linker
::linkKnown(
816 $this->msg( 'search-interwiki-more' )->text(),
820 'fulltext' => 'Search'
823 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
824 {$searchLink}</span>{$caption}</div>\n<ul>";
827 $out .= "<li>{$link} {$redirect}</li>\n";
828 wfProfileOut( __METHOD__
);
837 protected function getProfileForm( $profile, $term ) {
840 $opts['redirs'] = $this->searchRedirects
;
841 $opts['profile'] = $this->profile
;
843 if ( $profile === 'advanced' ) {
844 return $this->powerSearchBox( $term, $opts );
847 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
853 * Generates the power search box at [[Special:Search]]
855 * @param $term String: search term
857 * @return String: HTML form
859 protected function powerSearchBox( $term, $opts ) {
860 // Groups namespaces into rows according to subject
862 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
863 $subject = MWNamespace
::getSubject( $namespace );
864 if( !array_key_exists( $subject, $rows ) ) {
865 $rows[$subject] = "";
867 $name = str_replace( '_', ' ', $name );
869 $name = $this->msg( 'blanknamespace' )->text();
873 'td', array( 'style' => 'white-space: nowrap' )
878 "mw-search-ns{$namespace}",
879 in_array( $namespace, $this->namespaces
)
881 Xml
::closeElement( 'td' );
883 $rows = array_values( $rows );
884 $numRows = count( $rows );
886 // Lays out namespaces in multiple floating two-column tables so they'll
887 // be arranged nicely while still accommodating different screen widths
888 $namespaceTables = '';
889 for( $i = 0; $i < $numRows; $i +
= 4 ) {
890 $namespaceTables .= Xml
::openElement(
892 array( 'cellpadding' => 0, 'cellspacing' => 0 )
894 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
895 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
897 $namespaceTables .= Xml
::closeElement( 'table' );
900 $showSections = array( 'namespaceTables' => $namespaceTables );
902 // Show redirects check only if backend supports it
903 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
904 $showSections['redirects'] =
905 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
908 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
911 unset( $opts['redirs'] );
912 foreach( $opts as $key => $value ) {
913 $hidden .= Html
::hidden( $key, $value );
915 // Return final output
919 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
921 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
922 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
923 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
924 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
925 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
927 Xml
::closeElement( 'fieldset' );
933 protected function getSearchProfiles() {
934 // Builds list of Search Types (profiles)
935 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
939 'message' => 'searchprofile-articles',
940 'tooltip' => 'searchprofile-articles-tooltip',
941 'namespaces' => SearchEngine
::defaultNamespaces(),
942 'namespace-messages' => SearchEngine
::namespacesAsText(
943 SearchEngine
::defaultNamespaces()
947 'message' => 'searchprofile-images',
948 'tooltip' => 'searchprofile-images-tooltip',
949 'namespaces' => array( NS_FILE
),
952 'message' => 'searchprofile-project',
953 'tooltip' => 'searchprofile-project-tooltip',
954 'namespaces' => SearchEngine
::helpNamespaces(),
955 'namespace-messages' => SearchEngine
::namespacesAsText(
956 SearchEngine
::helpNamespaces()
960 'message' => 'searchprofile-everything',
961 'tooltip' => 'searchprofile-everything-tooltip',
962 'namespaces' => $nsAllSet,
965 'message' => 'searchprofile-advanced',
966 'tooltip' => 'searchprofile-advanced-tooltip',
967 'namespaces' => self
::NAMESPACES_CURRENT
,
971 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
973 foreach( $profiles as &$data ) {
974 if ( !is_array( $data['namespaces'] ) ) continue;
975 sort( $data['namespaces'] );
983 * @param $resultsShown
987 protected function formHeader( $term, $resultsShown, $totalNum ) {
988 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
991 if( $this->startsWithImage( $term ) ) {
993 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
996 $profiles = $this->getSearchProfiles();
997 $lang = $this->getLanguage();
999 // Outputs XML for Search Types
1000 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1001 $out .= Xml
::openElement( 'ul' );
1002 foreach ( $profiles as $id => $profile ) {
1003 if ( !isset( $profile['parameters'] ) ) {
1004 $profile['parameters'] = array();
1006 $profile['parameters']['profile'] = $id;
1008 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1009 $lang->commaList( $profile['namespace-messages'] ) : null;
1013 'class' => $this->profile
=== $id ?
'current' : 'normal'
1015 $this->makeSearchLink(
1018 $this->msg( $profile['message'] )->text(),
1019 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1020 $profile['parameters']
1024 $out .= Xml
::closeElement( 'ul' );
1025 $out .= Xml
::closeElement( 'div' );
1028 if ( $resultsShown > 0 ) {
1029 if ( $totalNum > 0 ) {
1030 $top = $this->msg( 'showingresultsheader' )
1031 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1032 ->params( wfEscapeWikiText( $term ) )
1033 ->numParams( $resultsShown )
1035 } elseif ( $resultsShown >= $this->limit
) {
1036 $top = $this->msg( 'showingresults' )
1037 ->numParams( $this->limit
, $this->offset +
1 )
1040 $top = $this->msg( 'showingresultsnum' )
1041 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1044 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1045 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1049 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1050 $out .= Xml
::closeElement( 'div' );
1056 * @param $term string
1059 protected function shortDialog( $term ) {
1060 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1061 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1063 $out .= Html
::input( 'search', $term, 'search', array(
1064 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1068 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1069 $out .= Xml
::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1070 return $out . $this->didYouMeanHtml
;
1074 * Make a search link with some target namespaces
1076 * @param $term String
1077 * @param $namespaces Array ignored
1078 * @param $label String: link's text
1079 * @param $tooltip String: link's tooltip
1080 * @param $params Array: query string parameters
1081 * @return String: HTML fragment
1083 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1085 foreach( $namespaces as $n ) {
1086 $opt['ns' . $n] = 1;
1088 $opt['redirs'] = $this->searchRedirects
;
1090 $stParams = array_merge(
1093 'fulltext' => $this->msg( 'search' )->text()
1098 return Xml
::element(
1101 'href' => $this->getTitle()->getLocalURL( $stParams ),
1102 'title' => $tooltip),
1108 * Check if query starts with image: prefix
1110 * @param $term String: the string to check
1113 protected function startsWithImage( $term ) {
1116 $p = explode( ':', $term );
1117 if( count( $p ) > 1 ) {
1118 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1124 * Check if query starts with all: prefix
1126 * @param $term String: the string to check
1129 protected function startsWithAll( $term ) {
1131 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1133 $p = explode( ':', $term );
1134 if( count( $p ) > 1 ) {
1135 return $p[0] == $allkeyword;
1143 * @return SearchEngine
1145 public function getSearchEngine() {
1146 if ( $this->searchEngine
=== null ) {
1147 $this->searchEngine
= SearchEngine
::create();
1149 return $this->searchEngine
;
1153 * Users of hook SpecialSearchSetupEngine can use this to
1154 * add more params to links to not lose selection when
1155 * user navigates search results.
1161 public function setExtraParam( $key, $value ) {
1162 $this->extraParams
[$key] = $value;