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>';
291 // start rendering the page
296 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
298 'action' => $wgScript
303 Xml
::openElement( 'table', array( 'id' => 'mw-search-top-table', 'cellpadding' => 0, 'cellspacing' => 0 ) ) .
304 Xml
::openElement( 'tr' ) .
305 Xml
::openElement( 'td' ) . "\n" .
306 $this->shortDialog( $term ) .
307 Xml
::closeElement('td') .
308 Xml
::closeElement('tr') .
309 Xml
::closeElement('table')
312 // Sometimes the search engine knows there are too many hits
313 if( $titleMatches instanceof SearchResultTooMany
) {
314 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
315 wfProfileOut( __METHOD__
);
319 $filePrefix = $wgContLang->getFormattedNsText(NS_FILE
).':';
320 if( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
321 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
322 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
323 $out->addHTML( '</form>' );
324 // Empty query -- straight view of search form
325 wfProfileOut( __METHOD__
);
329 // Get number of results
330 $titleMatchesNum = $titleMatches ?
$titleMatches->numRows() : 0;
331 $textMatchesNum = $textMatches ?
$textMatches->numRows() : 0;
332 // Total initial query matches (possible false positives)
333 $num = $titleMatchesNum +
$textMatchesNum;
335 // Get total actual results (after second filtering, if any)
336 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
337 $titleMatches->getTotalHits() : $titleMatchesNum;
338 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
339 $textMatches->getTotalHits() : $textMatchesNum;
341 // get total number of results if backend can calculate it
343 if($titleMatches && !is_null( $titleMatches->getTotalHits() ) )
344 $totalRes +
= $titleMatches->getTotalHits();
345 if($textMatches && !is_null( $textMatches->getTotalHits() ))
346 $totalRes +
= $textMatches->getTotalHits();
348 // show number of results and current offset
349 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
350 $out->addHtml( $this->getProfileForm( $this->profile
, $term ) );
353 $out->addHtml( Xml
::closeElement( 'form' ) );
354 $out->addHtml( "<div class='searchresults'>" );
357 if( $num ||
$this->offset
) {
358 // Show the create link ahead
359 $this->showCreateLink( $t );
360 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset
, $this->limit
,
361 $this->powerSearchOptions() +
array( 'search' => $term ),
362 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
364 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
365 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
367 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
370 $out->parserOptions()->setEditSection( false );
371 if( $titleMatches ) {
372 if( $numTitleMatches > 0 ) {
373 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
374 $out->addHTML( $this->showMatches( $titleMatches ) );
376 $titleMatches->free();
379 // output appropriate heading
380 if( $numTextMatches > 0 && $numTitleMatches > 0 ) {
381 // if no title matches the heading is redundant
382 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
383 } elseif( $totalRes == 0 ) {
384 # Don't show the 'no text matches' if we received title matches
385 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
387 // show interwiki results if any
388 if( $textMatches->hasInterwikiResults() ) {
389 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
392 if( $numTextMatches > 0 ) {
393 $out->addHTML( $this->showMatches( $textMatches ) );
396 $textMatches->free();
399 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
400 $this->showCreateLink( $t );
402 $out->addHtml( "</div>" );
404 if( $num ||
$this->offset
) {
405 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
407 wfProfileOut( __METHOD__
);
413 protected function showCreateLink( $t ) {
414 // show direct page/create link if applicable
416 // Check DBkey !== '' in case of fragment link only.
417 if( is_null( $t ) ||
$t->getDBkey() === '' ) {
419 // preserve the paragraph for margins etc...
420 $this->getOutput()->addHtml( '<p></p>' );
424 if( $t->isKnown() ) {
425 $messageName = 'searchmenu-exists';
426 } elseif( $t->userCan( 'create' ) ) {
427 $messageName = 'searchmenu-new';
429 $messageName = 'searchmenu-new-nocreate';
431 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
432 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
434 // Extensions using the hook might still return an empty $messageName
436 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
438 // preserve the paragraph for margins etc...
439 $this->getOutput()->addHtml( '<p></p>' );
444 * @param $term string
446 protected function setupPage( $term ) {
447 # Should advanced UI be used?
448 $this->searchAdvanced
= ($this->profile
=== 'advanced');
449 $out = $this->getOutput();
450 if( strval( $term ) !== '' ) {
451 $out->setPageTitle( $this->msg( 'searchresults' ) );
452 $out->setHTMLTitle( $this->msg( 'pagetitle', $this->msg( 'searchresults-title', $term )->plain() ) );
454 // add javascript specific to special:search
455 $out->addModules( 'mediawiki.special.search' );
459 * Extract "power search" namespace settings from the request object,
460 * returning a list of index numbers to search.
462 * @param $request WebRequest
465 protected function powerSearch( &$request ) {
467 foreach( SearchEngine
::searchableNamespaces() as $ns => $name ) {
468 if( $request->getCheck( 'ns' . $ns ) ) {
477 * Reconstruct the 'power search' options for links
481 protected function powerSearchOptions() {
483 $opt['redirs'] = $this->searchRedirects ?
1 : 0;
484 if( $this->profile
!== 'advanced' ) {
485 $opt['profile'] = $this->profile
;
487 foreach( $this->namespaces
as $n ) {
491 return $opt +
$this->extraParams
;
495 * Show whole set of results
497 * @param $matches SearchResultSet
501 protected function showMatches( &$matches ) {
503 wfProfileIn( __METHOD__
);
505 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
508 $infoLine = $matches->getInfo();
509 if( !is_null($infoLine) ) {
510 $out .= "\n<!-- {$infoLine} -->\n";
512 $out .= "<ul class='mw-search-results'>\n";
513 $result = $matches->next();
515 $out .= $this->showHit( $result, $terms );
516 $result = $matches->next();
520 // convert the whole thing to desired language variant
521 $out = $wgContLang->convert( $out );
522 wfProfileOut( __METHOD__
);
527 * Format a single hit result
529 * @param $result SearchResult
530 * @param $terms Array: terms to highlight
534 protected function showHit( $result, $terms ) {
535 wfProfileIn( __METHOD__
);
537 if( $result->isBrokenTitle() ) {
538 wfProfileOut( __METHOD__
);
539 return "<!-- Broken link in search result -->\n";
542 $t = $result->getTitle();
544 $titleSnippet = $result->getTitleSnippet($terms);
546 if( $titleSnippet == '' )
547 $titleSnippet = null;
551 wfRunHooks( 'ShowSearchHitTitle',
552 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
554 $link = Linker
::linkKnown(
559 //If page content is not readable, just return the title.
560 //This is not quite safe, but better than showing excerpts from non-readable pages
561 //Note that hiding the entry entirely would screw up paging.
562 if( !$t->userCan( 'read' ) ) {
563 wfProfileOut( __METHOD__
);
564 return "<li>{$link}</li>\n";
567 // If the page doesn't *exist*... our search index is out of date.
568 // The least confusing at this point is to drop the result.
569 // You may get less results, but... oh well. :P
570 if( $result->isMissingRevision() ) {
571 wfProfileOut( __METHOD__
);
572 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
575 // format redirects / relevant sections
576 $redirectTitle = $result->getRedirectTitle();
577 $redirectText = $result->getRedirectSnippet($terms);
578 $sectionTitle = $result->getSectionTitle();
579 $sectionText = $result->getSectionSnippet($terms);
582 if( !is_null($redirectTitle) ) {
583 if( $redirectText == '' )
584 $redirectText = null;
586 $redirect = "<span class='searchalttitle'>" .
587 $this->msg( 'search-redirect' )->rawParams(
588 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
594 if( !is_null($sectionTitle) ) {
595 if( $sectionText == '' )
598 $section = "<span class='searchalttitle'>" .
599 $this->msg( 'search-section' )->rawParams(
600 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
604 // format text extract
605 $extract = "<div class='searchresult'>".$result->getTextSnippet($terms)."</div>";
607 $lang = $this->getLanguage();
610 if( is_null( $result->getScore() ) ) {
611 // Search engine doesn't report scoring info
614 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
615 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
619 // format description
620 $byteSize = $result->getByteSize();
621 $wordCount = $result->getWordCount();
622 $timestamp = $result->getTimestamp();
623 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
624 ->numParams( $wordCount )->escaped();
626 if( $t->getNamespace() == NS_CATEGORY
) {
627 $cat = Category
::newFromTitle( $t );
628 $size = $this->msg( 'search-result-category-size' )
629 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
633 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
635 // link to related articles if supported
637 if( $result->hasRelated() ) {
638 $st = SpecialPage
::getTitleFor( 'Search' );
639 $stParams = array_merge(
640 $this->powerSearchOptions(),
642 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
643 ':' . $t->getPrefixedText(),
644 'fulltext' => $this->msg( 'search' )->text()
648 $related = ' -- ' . Linker
::linkKnown(
650 $this->msg( 'search-relatedarticle' )->text(),
656 // Include a thumbnail for media files...
657 if( $t->getNamespace() == NS_FILE
) {
658 $img = wfFindFile( $t );
660 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
662 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
663 wfProfileOut( __METHOD__
);
664 // Float doesn't seem to interact well with the bullets.
665 // Table messes up vertical alignment of the bullets.
666 // Bullets are therefore disabled (didn't look great anyway).
668 '<table class="searchResultImage">' .
670 '<td width="120" style="text-align: center; vertical-align: top;">' .
671 $thumb->toHtml( array( 'desc-link' => true ) ) .
673 '<td style="vertical-align: top;">' .
676 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
685 wfProfileOut( __METHOD__
);
686 return "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
687 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
693 * Show results from other wikis
695 * @param $matches SearchResultSet
696 * @param $query String
700 protected function showInterwiki( &$matches, $query ) {
702 wfProfileIn( __METHOD__
);
703 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
705 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>".
706 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
707 $out .= "<ul class='mw-search-iwresults'>\n";
709 // work out custom project captions
710 $customCaptions = array();
711 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
712 foreach($customLines as $line) {
713 $parts = explode(":",$line,2);
714 if(count($parts) == 2) // validate line
715 $customCaptions[$parts[0]] = $parts[1];
719 $result = $matches->next();
721 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
722 $prev = $result->getInterwikiPrefix();
723 $result = $matches->next();
725 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
726 $out .= "</ul></div>\n";
728 // convert the whole thing to desired language variant
729 $out = $wgContLang->convert( $out );
730 wfProfileOut( __METHOD__
);
735 * Show single interwiki link
737 * @param $result SearchResult
738 * @param $lastInterwiki String
739 * @param $terms Array
740 * @param $query String
741 * @param $customCaptions Array: iw prefix -> caption
745 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions) {
746 wfProfileIn( __METHOD__
);
748 if( $result->isBrokenTitle() ) {
749 wfProfileOut( __METHOD__
);
750 return "<!-- Broken link in search result -->\n";
753 $t = $result->getTitle();
755 $titleSnippet = $result->getTitleSnippet($terms);
757 if( $titleSnippet == '' )
758 $titleSnippet = null;
760 $link = Linker
::linkKnown(
765 // format redirect if any
766 $redirectTitle = $result->getRedirectTitle();
767 $redirectText = $result->getRedirectSnippet($terms);
769 if( !is_null($redirectTitle) ) {
770 if( $redirectText == '' )
771 $redirectText = null;
773 $redirect = "<span class='searchalttitle'>" .
774 $this->msg( 'search-redirect' )->rawParams(
775 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
780 // display project name
781 if(is_null($lastInterwiki) ||
$lastInterwiki != $t->getInterwiki()) {
782 if( array_key_exists($t->getInterwiki(),$customCaptions) ) {
783 // captions from 'search-interwiki-custom'
784 $caption = $customCaptions[$t->getInterwiki()];
786 // default is to show the hostname of the other wiki which might suck
787 // if there are many wikis on one hostname
788 $parsed = wfParseUrl( $t->getFullURL() );
789 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
791 // "more results" link (special page stuff could be localized, but we might not know target lang)
792 $searchTitle = Title
::newFromText($t->getInterwiki().":Special:Search");
793 $searchLink = Linker
::linkKnown(
795 $this->msg( 'search-interwiki-more' )->text(),
799 'fulltext' => 'Search'
802 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
803 {$searchLink}</span>{$caption}</div>\n<ul>";
806 $out .= "<li>{$link} {$redirect}</li>\n";
807 wfProfileOut( __METHOD__
);
816 protected function getProfileForm( $profile, $term ) {
819 $opts['redirs'] = $this->searchRedirects
;
820 $opts['profile'] = $this->profile
;
822 if ( $profile === 'advanced' ) {
823 return $this->powerSearchBox( $term, $opts );
826 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
832 * Generates the power search box at [[Special:Search]]
834 * @param $term String: search term
836 * @return String: HTML form
838 protected function powerSearchBox( $term, $opts ) {
839 // Groups namespaces into rows according to subject
841 foreach( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
842 $subject = MWNamespace
::getSubject( $namespace );
843 if( !array_key_exists( $subject, $rows ) ) {
844 $rows[$subject] = "";
846 $name = str_replace( '_', ' ', $name );
848 $name = $this->msg( 'blanknamespace' )->text();
852 'td', array( 'style' => 'white-space: nowrap' )
857 "mw-search-ns{$namespace}",
858 in_array( $namespace, $this->namespaces
)
860 Xml
::closeElement( 'td' );
862 $rows = array_values( $rows );
863 $numRows = count( $rows );
865 // Lays out namespaces in multiple floating two-column tables so they'll
866 // be arranged nicely while still accommodating different screen widths
867 $namespaceTables = '';
868 for( $i = 0; $i < $numRows; $i +
= 4 ) {
869 $namespaceTables .= Xml
::openElement(
871 array( 'cellpadding' => 0, 'cellspacing' => 0 )
873 for( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
874 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
876 $namespaceTables .= Xml
::closeElement( 'table' );
879 $showSections = array( 'namespaceTables' => $namespaceTables );
881 // Show redirects check only if backend supports it
882 if( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
883 $showSections['redirects'] =
884 Xml
::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects
);
887 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
890 unset( $opts['redirs'] );
891 foreach( $opts as $key => $value ) {
892 $hidden .= Html
::hidden( $key, $value );
894 // Return final output
898 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
900 Xml
::element( 'legend', null, $this->msg('powersearch-legend' )->text() ) .
901 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
902 Html
::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
903 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
904 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
906 Xml
::closeElement( 'fieldset' );
912 protected function getSearchProfiles() {
913 // Builds list of Search Types (profiles)
914 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
918 'message' => 'searchprofile-articles',
919 'tooltip' => 'searchprofile-articles-tooltip',
920 'namespaces' => SearchEngine
::defaultNamespaces(),
921 'namespace-messages' => SearchEngine
::namespacesAsText(
922 SearchEngine
::defaultNamespaces()
926 'message' => 'searchprofile-images',
927 'tooltip' => 'searchprofile-images-tooltip',
928 'namespaces' => array( NS_FILE
),
931 'message' => 'searchprofile-project',
932 'tooltip' => 'searchprofile-project-tooltip',
933 'namespaces' => SearchEngine
::helpNamespaces(),
934 'namespace-messages' => SearchEngine
::namespacesAsText(
935 SearchEngine
::helpNamespaces()
939 'message' => 'searchprofile-everything',
940 'tooltip' => 'searchprofile-everything-tooltip',
941 'namespaces' => $nsAllSet,
944 'message' => 'searchprofile-advanced',
945 'tooltip' => 'searchprofile-advanced-tooltip',
946 'namespaces' => self
::NAMESPACES_CURRENT
,
950 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
952 foreach( $profiles as &$data ) {
953 if ( !is_array( $data['namespaces'] ) ) continue;
954 sort( $data['namespaces'] );
962 * @param $resultsShown
966 protected function formHeader( $term, $resultsShown, $totalNum ) {
967 $out = Xml
::openElement('div', array( 'class' => 'mw-search-formheader' ) );
970 if( $this->startsWithImage( $term ) ) {
972 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
975 $profiles = $this->getSearchProfiles();
976 $lang = $this->getLanguage();
978 // Outputs XML for Search Types
979 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
980 $out .= Xml
::openElement( 'ul' );
981 foreach ( $profiles as $id => $profile ) {
982 if ( !isset( $profile['parameters'] ) ) {
983 $profile['parameters'] = array();
985 $profile['parameters']['profile'] = $id;
987 $tooltipParam = isset( $profile['namespace-messages'] ) ?
988 $lang->commaList( $profile['namespace-messages'] ) : null;
992 'class' => $this->profile
=== $id ?
'current' : 'normal'
994 $this->makeSearchLink(
997 $this->msg( $profile['message'] )->text(),
998 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
999 $profile['parameters']
1003 $out .= Xml
::closeElement( 'ul' );
1004 $out .= Xml
::closeElement('div') ;
1007 if ( $resultsShown > 0 ) {
1008 if ( $totalNum > 0 ){
1009 $top = $this->msg( 'showingresultsheader' )
1010 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1011 ->params( wfEscapeWikiText( $term ) )
1012 ->numParams( $resultsShown )
1014 } elseif ( $resultsShown >= $this->limit
) {
1015 $top = $this->msg( 'showingresults' )
1016 ->numParams( $this->limit
, $this->offset +
1 )
1019 $top = $this->msg( 'showingresultsnum' )
1020 ->numParams( $this->limit
, $this->offset +
1, $resultsShown )
1023 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ),
1024 Xml
::tags( 'ul', null, Xml
::tags( 'li', null, $top ) )
1028 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1029 $out .= Xml
::closeElement('div');
1035 * @param $term string
1038 protected function shortDialog( $term ) {
1039 $out = Html
::hidden( 'title', $this->getTitle()->getPrefixedText() );
1040 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1042 $out .= Html
::input( 'search', $term, 'search', array(
1043 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1047 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1048 $out .= Xml
::submitButton( $this->msg( 'searchbutton' )->text() ) . "\n";
1049 return $out . $this->didYouMeanHtml
;
1053 * Make a search link with some target namespaces
1055 * @param $term String
1056 * @param $namespaces Array ignored
1057 * @param $label String: link's text
1058 * @param $tooltip String: link's tooltip
1059 * @param $params Array: query string parameters
1060 * @return String: HTML fragment
1062 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1064 foreach( $namespaces as $n ) {
1065 $opt['ns' . $n] = 1;
1067 $opt['redirs'] = $this->searchRedirects
;
1069 $stParams = array_merge(
1072 'fulltext' => $this->msg( 'search' )->text()
1077 return Xml
::element(
1080 'href' => $this->getTitle()->getLocalURL( $stParams ),
1081 'title' => $tooltip),
1087 * Check if query starts with image: prefix
1089 * @param $term String: the string to check
1092 protected function startsWithImage( $term ) {
1095 $p = explode( ':', $term );
1096 if( count( $p ) > 1 ) {
1097 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE
;
1103 * Check if query starts with all: prefix
1105 * @param $term String: the string to check
1108 protected function startsWithAll( $term ) {
1110 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1112 $p = explode( ':', $term );
1113 if( count( $p ) > 1 ) {
1114 return $p[0] == $allkeyword;
1122 * @return SearchEngine
1124 public function getSearchEngine() {
1125 if ( $this->searchEngine
=== null ) {
1126 $this->searchEngine
= SearchEngine
::create();
1128 return $this->searchEngine
;
1132 * Users of hook SpecialSearchSetupEngine can use this to
1133 * add more params to links to not lose selection when
1134 * user navigates search results.
1140 public function setExtraParam( $key, $value ) {
1141 $this->extraParams
[$key] = $value;