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',
89 // Strip underscores from title parameter; most of the time we'll want
90 // text form here. But don't strip underscores from actual text params!
91 $titleParam = str_replace( '_', ' ', $par );
93 $request = $this->getRequest();
95 // Fetch the search term
96 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
99 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
100 $this->saveNamespaces();
101 // Remove the token from the URL to prevent the user from inadvertently
102 // exposing it (e.g. by pasting it into a public wiki page) or undoing
103 // later settings changes (e.g. by reloading the page).
104 $query = $request->getValues();
105 unset( $query['title'], $query['nsRemember'] );
106 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
110 $this->searchEngineType
= $request->getVal( 'srbackend' );
112 if ( $request->getVal( 'fulltext' )
113 ||
!is_null( $request->getVal( 'offset' ) )
115 $this->showResults( $search );
117 $this->goResult( $search );
122 * Set up basic search parameters from the request and user settings.
124 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
126 public function load() {
127 $request = $this->getRequest();
128 list( $this->limit
, $this->offset
) = $request->getLimitOffset( 20, '' );
129 $this->mPrefix
= $request->getVal( 'prefix', '' );
131 $user = $this->getUser();
133 # Extract manually requested namespaces
134 $nslist = $this->powerSearch( $request );
135 if ( !count( $nslist ) ) {
136 # Fallback to user preference
137 $nslist = SearchEngine
::userNamespaces( $user );
141 if ( !count( $nslist ) ) {
142 $profile = 'default';
145 $profile = $request->getVal( 'profile', $profile );
146 $profiles = $this->getSearchProfiles();
147 if ( $profile === null ) {
148 // BC with old request format
149 $profile = 'advanced';
150 foreach ( $profiles as $key => $data ) {
151 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
155 $this->namespaces
= $nslist;
156 } elseif ( $profile === 'advanced' ) {
157 $this->namespaces
= $nslist;
159 if ( isset( $profiles[$profile]['namespaces'] ) ) {
160 $this->namespaces
= $profiles[$profile]['namespaces'];
162 // Unknown profile requested
163 $profile = 'default';
164 $this->namespaces
= $profiles['default']['namespaces'];
168 $this->didYouMeanHtml
= ''; # html of did you mean... link
169 $this->fulltext
= $request->getVal( 'fulltext' );
170 $this->profile
= $profile;
174 * If an exact title match can be found, jump straight ahead to it.
176 * @param string $term
178 public function goResult( $term ) {
179 $this->setupPage( $term );
180 # Try to go to page as entered.
181 $title = Title
::newFromText( $term );
182 # If the string cannot be used to create a title
183 if ( is_null( $title ) ) {
184 $this->showResults( $term );
188 # If there's an exact or very near match, jump right there.
189 $title = SearchEngine
::getNearMatch( $term );
191 if ( !is_null( $title ) ) {
192 $this->getOutput()->redirect( $title->getFullURL() );
196 # No match, generate an edit URL
197 $title = Title
::newFromText( $term );
198 if ( !is_null( $title ) ) {
199 wfRunHooks( 'SpecialSearchNogomatch', array( &$title ) );
200 wfDebugLog( 'nogomatch', $title->getFullText(), 'private' );
202 # If the feature is enabled, go straight to the edit page
203 if ( $this->getConfig()->get( 'GoToEdit' ) ) {
204 $this->getOutput()->redirect( $title->getFullURL( array( 'action' => 'edit' ) ) );
209 $this->showResults( $term );
213 * @param string $term
215 public function showResults( $term ) {
218 $profile = new ProfileSection( __METHOD__
);
219 $search = $this->getSearchEngine();
220 $search->setLimitOffset( $this->limit
, $this->offset
);
221 $search->setNamespaces( $this->namespaces
);
222 $search->prefix
= $this->mPrefix
;
223 $term = $search->transformSearchTerm( $term );
225 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile
, $search ) );
227 $this->setupPage( $term );
229 $out = $this->getOutput();
231 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
232 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
233 if ( $searchFowardUrl ) {
234 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
235 $out->redirect( $url );
238 Xml
::openElement( 'fieldset' ) .
239 Xml
::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
242 array( 'class' => 'mw-searchdisabled' ),
243 $this->msg( 'searchdisabled' )->text()
245 $this->msg( 'googlesearch' )->rawParams(
246 htmlspecialchars( $term ),
248 $this->msg( 'searchbutton' )->escaped()
250 Xml
::closeElement( 'fieldset' )
257 $title = Title
::newFromText( $term );
258 $showSuggestion = $title === null ||
!$title->isKnown();
259 $search->setShowSuggestion( $showSuggestion );
261 // fetch search results
262 $rewritten = $search->replacePrefixes( $term );
264 $titleMatches = $search->searchTitle( $rewritten );
265 $textMatches = $search->searchText( $rewritten );
268 if ( $textMatches instanceof Status
) {
269 $textStatus = $textMatches;
273 // did you mean... suggestions
274 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
275 # mirror Go/Search behavior of original request ..
276 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
278 if ( $this->fulltext
!= null ) {
279 $didYouMeanParams['fulltext'] = $this->fulltext
;
282 $stParams = array_merge(
284 $this->powerSearchOptions()
287 $suggestionSnippet = $textMatches->getSuggestionSnippet();
289 if ( $suggestionSnippet == '' ) {
290 $suggestionSnippet = null;
293 $suggestLink = Linker
::linkKnown(
294 $this->getPageTitle(),
300 $this->didYouMeanHtml
= '<div class="searchdidyoumean">'
301 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
304 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
305 # Hook requested termination
309 // start rendering the page
314 'id' => ( $this->profile
=== 'advanced' ?
'powersearch' : 'search' ),
316 'action' => wfScript(),
321 // Get number of results
322 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
323 if ( $titleMatches ) {
324 $titleMatchesNum = $titleMatches->numRows();
325 $numTitleMatches = $titleMatches->getTotalHits();
327 if ( $textMatches ) {
328 $textMatchesNum = $textMatches->numRows();
329 $numTextMatches = $textMatches->getTotalHits();
331 $num = $titleMatchesNum +
$textMatchesNum;
332 $totalRes = $numTitleMatches +
$numTextMatches;
335 # This is an awful awful ID name. It's not a table, but we
336 # named it poorly from when this was a table so now we're
338 Xml
::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
339 $this->shortDialog( $term, $num, $totalRes ) .
340 Xml
::closeElement( 'div' ) .
341 $this->formHeader( $term ) .
342 Xml
::closeElement( 'form' )
345 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE
) . ':';
346 if ( trim( $term ) === '' ||
$filePrefix === trim( $term ) ) {
347 // Empty query -- straight view of search form
351 $out->addHtml( "<div class='searchresults'>" );
355 if ( $num ||
$this->offset
) {
356 // Show the create link ahead
357 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
358 if ( $totalRes > $this->limit ||
$this->offset
) {
359 if ( $this->searchEngineType
!== null ) {
360 $this->setExtraParam( 'srbackend', $this->searchEngineType
);
362 $prevnext = $this->getLanguage()->viewPrevNext(
363 $this->getPageTitle(),
366 $this->powerSearchOptions() +
array( 'search' => $term ),
367 $this->limit +
$this->offset
>= $totalRes
371 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
373 $out->parserOptions()->setEditSection( false );
374 if ( $titleMatches ) {
375 if ( $numTitleMatches > 0 ) {
376 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
377 $out->addHTML( $this->showMatches( $titleMatches ) );
379 $titleMatches->free();
381 if ( $textMatches && !$textStatus ) {
382 // output appropriate heading
383 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
384 // if no title matches the heading is redundant
385 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
388 // show interwiki results if any
389 if ( $textMatches->hasInterwikiResults() ) {
390 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
393 if ( $numTextMatches > 0 ) {
394 $out->addHTML( $this->showMatches( $textMatches ) );
397 $textMatches->free();
401 $out->addHTML( '<div class="error">' .
402 $textStatus->getMessage( 'search-error' ) . '</div>' );
404 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
405 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
406 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
409 $out->addHtml( "</div>" );
412 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
417 * @param Title $title
418 * @param int $num The number of search results found
419 * @param null|SearchResultSet $titleMatches Results from title search
420 * @param null|SearchResultSet $textMatches Results from text search
422 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
423 // show direct page/create link if applicable
425 // Check DBkey !== '' in case of fragment link only.
426 if ( is_null( $title ) ||
$title->getDBkey() === ''
427 ||
( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
428 ||
( $textMatches !== null && $textMatches->searchContainedSyntax() )
431 // preserve the paragraph for margins etc...
432 $this->getOutput()->addHtml( '<p></p>' );
437 $linkClass = 'mw-search-createlink';
438 if ( $title->isKnown() ) {
439 $messageName = 'searchmenu-exists';
440 $linkClass = 'mw-search-exists';
441 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
442 $messageName = 'searchmenu-new';
444 $messageName = 'searchmenu-new-nocreate';
448 wfEscapeWikiText( $title->getPrefixedText() ),
449 Message
::numParam( $num )
451 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
453 // Extensions using the hook might still return an empty $messageName
454 if ( $messageName ) {
455 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
457 // preserve the paragraph for margins etc...
458 $this->getOutput()->addHtml( '<p></p>' );
463 * @param string $term
465 protected function setupPage( $term ) {
466 # Should advanced UI be used?
467 $this->searchAdvanced
= ( $this->profile
=== 'advanced' );
468 $out = $this->getOutput();
469 if ( strval( $term ) !== '' ) {
470 $out->setPageTitle( $this->msg( 'searchresults' ) );
471 $out->setHTMLTitle( $this->msg( 'pagetitle' )
472 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
473 ->inContentLanguage()->text()
476 // add javascript specific to special:search
477 $out->addModules( 'mediawiki.special.search' );
481 * Extract "power search" namespace settings from the request object,
482 * returning a list of index numbers to search.
484 * @param WebRequest $request
487 protected function powerSearch( &$request ) {
489 foreach ( SearchEngine
::searchableNamespaces() as $ns => $name ) {
490 if ( $request->getCheck( 'ns' . $ns ) ) {
499 * Reconstruct the 'power search' options for links
503 protected function powerSearchOptions() {
505 if ( $this->profile
!== 'advanced' ) {
506 $opt['profile'] = $this->profile
;
508 foreach ( $this->namespaces
as $n ) {
513 return $opt +
$this->extraParams
;
517 * Save namespace preferences when we're supposed to
519 * @return bool Whether we wrote something
521 protected function saveNamespaces() {
522 $user = $this->getUser();
523 $request = $this->getRequest();
525 if ( $user->isLoggedIn() &&
526 $user->matchEditToken(
527 $request->getVal( 'nsRemember' ),
532 // Reset namespace preferences: namespaces are not searched
533 // when they're not mentioned in the URL parameters.
534 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
535 $user->setOption( 'searchNs' . $n, false );
537 // The request parameters include all the namespaces to be searched.
538 // Even if they're the same as an existing profile, they're not eaten.
539 foreach ( $this->namespaces
as $n ) {
540 $user->setOption( 'searchNs' . $n, true );
543 $user->saveSettings();
551 * Show whole set of results
553 * @param SearchResultSet $matches
557 protected function showMatches( &$matches ) {
560 $profile = new ProfileSection( __METHOD__
);
561 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
563 $out = "<ul class='mw-search-results'>\n";
564 $result = $matches->next();
566 $out .= $this->showHit( $result, $terms );
567 $result = $matches->next();
571 // convert the whole thing to desired language variant
572 $out = $wgContLang->convert( $out );
578 * Format a single hit result
580 * @param SearchResult $result
581 * @param array $terms Terms to highlight
585 protected function showHit( $result, $terms ) {
586 $profile = new ProfileSection( __METHOD__
);
588 if ( $result->isBrokenTitle() ) {
592 $title = $result->getTitle();
594 $titleSnippet = $result->getTitleSnippet( $terms );
596 if ( $titleSnippet == '' ) {
597 $titleSnippet = null;
600 $link_t = clone $title;
602 wfRunHooks( 'ShowSearchHitTitle',
603 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
605 $link = Linker
::linkKnown(
610 //If page content is not readable, just return the title.
611 //This is not quite safe, but better than showing excerpts from non-readable pages
612 //Note that hiding the entry entirely would screw up paging.
613 if ( !$title->userCan( 'read', $this->getUser() ) ) {
614 return "<li>{$link}</li>\n";
617 // If the page doesn't *exist*... our search index is out of date.
618 // The least confusing at this point is to drop the result.
619 // You may get less results, but... oh well. :P
620 if ( $result->isMissingRevision() ) {
624 // format redirects / relevant sections
625 $redirectTitle = $result->getRedirectTitle();
626 $redirectText = $result->getRedirectSnippet( $terms );
627 $sectionTitle = $result->getSectionTitle();
628 $sectionText = $result->getSectionSnippet( $terms );
631 if ( !is_null( $redirectTitle ) ) {
632 if ( $redirectText == '' ) {
633 $redirectText = null;
636 $redirect = "<span class='searchalttitle'>" .
637 $this->msg( 'search-redirect' )->rawParams(
638 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
644 if ( !is_null( $sectionTitle ) ) {
645 if ( $sectionText == '' ) {
649 $section = "<span class='searchalttitle'>" .
650 $this->msg( 'search-section' )->rawParams(
651 Linker
::linkKnown( $sectionTitle, $sectionText ) )->text() .
655 // format text extract
656 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
658 $lang = $this->getLanguage();
660 // format description
661 $byteSize = $result->getByteSize();
662 $wordCount = $result->getWordCount();
663 $timestamp = $result->getTimestamp();
664 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
665 ->numParams( $wordCount )->escaped();
667 if ( $title->getNamespace() == NS_CATEGORY
) {
668 $cat = Category
::newFromTitle( $title );
669 $size = $this->msg( 'search-result-category-size' )
670 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
674 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
676 // link to related articles if supported
678 if ( $result->hasRelated() ) {
679 $stParams = array_merge(
680 $this->powerSearchOptions(),
682 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
683 ':' . $title->getPrefixedText(),
684 'fulltext' => $this->msg( 'search' )->text()
688 $related = ' -- ' . Linker
::linkKnown(
689 $this->getPageTitle(),
690 $this->msg( 'search-relatedarticle' )->text(),
697 // Include a thumbnail for media files...
698 if ( $title->getNamespace() == NS_FILE
) {
699 $img = $result->getFile();
700 $img = $img ?
: wfFindFile( $title );
701 if ( $result->isFileMatch() ) {
702 $fileMatch = "<span class='searchalttitle'>" .
703 $this->msg( 'search-file-match' )->escaped() . "</span>";
706 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
708 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
709 // Float doesn't seem to interact well with the bullets.
710 // Table messes up vertical alignment of the bullets.
711 // Bullets are therefore disabled (didn't look great anyway).
713 '<table class="searchResultImage">' .
715 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
716 $thumb->toHtml( array( 'desc-link' => true ) ) .
718 '<td style="vertical-align: top;">' .
719 "{$link} {$redirect} {$section} {$fileMatch}" .
721 "<div class='mw-search-result-data'>{$desc} - {$date}{$related}</div>" .
733 if ( wfRunHooks( 'ShowSearchHit', array(
734 $this, $result, $terms,
735 &$link, &$redirect, &$section, &$extract,
736 &$score, &$size, &$date, &$related,
739 $html = "<li><div class='mw-search-result-heading'>" .
740 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
741 "<div class='mw-search-result-data'>{$size} - {$date}{$related}</div>" .
749 * Show results from other wikis
751 * @param SearchResultSet|array $matches
752 * @param string $query
756 protected function showInterwiki( $matches, $query ) {
758 $profile = new ProfileSection( __METHOD__
);
760 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
761 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
762 $out .= "<ul class='mw-search-iwresults'>\n";
764 // work out custom project captions
765 $customCaptions = array();
766 // format per line <iwprefix>:<caption>
767 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
768 foreach ( $customLines as $line ) {
769 $parts = explode( ":", $line, 2 );
770 if ( count( $parts ) == 2 ) { // validate line
771 $customCaptions[$parts[0]] = $parts[1];
775 if ( !is_array( $matches ) ) {
776 $matches = array( $matches );
779 foreach ( $matches as $set ) {
781 $result = $set->next();
783 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
784 $prev = $result->getInterwikiPrefix();
785 $result = $set->next();
789 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
790 $out .= "</ul></div>\n";
792 // convert the whole thing to desired language variant
793 $out = $wgContLang->convert( $out );
799 * Show single interwiki link
801 * @param SearchResult $result
802 * @param string $lastInterwiki
803 * @param string $query
804 * @param array $customCaptions Interwiki prefix -> caption
808 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
809 $profile = new ProfileSection( __METHOD__
);
811 if ( $result->isBrokenTitle() ) {
815 $title = $result->getTitle();
817 $titleSnippet = $result->getTitleSnippet();
819 if ( $titleSnippet == '' ) {
820 $titleSnippet = null;
823 $link = Linker
::linkKnown(
828 // format redirect if any
829 $redirectTitle = $result->getRedirectTitle();
830 $redirectText = $result->getRedirectSnippet();
832 if ( !is_null( $redirectTitle ) ) {
833 if ( $redirectText == '' ) {
834 $redirectText = null;
837 $redirect = "<span class='searchalttitle'>" .
838 $this->msg( 'search-redirect' )->rawParams(
839 Linker
::linkKnown( $redirectTitle, $redirectText ) )->text() .
844 // display project name
845 if ( is_null( $lastInterwiki ) ||
$lastInterwiki != $title->getInterwiki() ) {
846 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
847 // captions from 'search-interwiki-custom'
848 $caption = $customCaptions[$title->getInterwiki()];
850 // default is to show the hostname of the other wiki which might suck
851 // if there are many wikis on one hostname
852 $parsed = wfParseUrl( $title->getFullURL() );
853 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
855 // "more results" link (special page stuff could be localized, but we might not know target lang)
856 $searchTitle = Title
::newFromText( $title->getInterwiki() . ":Special:Search" );
857 $searchLink = Linker
::linkKnown(
859 $this->msg( 'search-interwiki-more' )->text(),
863 'fulltext' => 'Search'
866 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
867 {$searchLink}</span>{$caption}</div>\n<ul>";
870 $out .= "<li>{$link} {$redirect}</li>\n";
876 * Generates the power search box at [[Special:Search]]
878 * @param string $term Search term
880 * @return string HTML form
882 protected function powerSearchBox( $term, $opts ) {
885 // Groups namespaces into rows according to subject
887 foreach ( SearchEngine
::searchableNamespaces() as $namespace => $name ) {
888 $subject = MWNamespace
::getSubject( $namespace );
889 if ( !array_key_exists( $subject, $rows ) ) {
890 $rows[$subject] = "";
893 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
895 $name = $this->msg( 'blanknamespace' )->text();
899 Xml
::openElement( 'td' ) .
903 "mw-search-ns{$namespace}",
904 in_array( $namespace, $this->namespaces
)
906 Xml
::closeElement( 'td' );
909 $rows = array_values( $rows );
910 $numRows = count( $rows );
912 // Lays out namespaces in multiple floating two-column tables so they'll
913 // be arranged nicely while still accommodating different screen widths
914 $namespaceTables = '';
915 for ( $i = 0; $i < $numRows; $i +
= 4 ) {
916 $namespaceTables .= Xml
::openElement(
918 array( 'cellpadding' => 0, 'cellspacing' => 0 )
921 for ( $j = $i; $j < $i +
4 && $j < $numRows; $j++
) {
922 $namespaceTables .= Xml
::tags( 'tr', null, $rows[$j] );
925 $namespaceTables .= Xml
::closeElement( 'table' );
928 $showSections = array( 'namespaceTables' => $namespaceTables );
930 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
933 foreach ( $opts as $key => $value ) {
934 $hidden .= Html
::hidden( $key, $value );
937 # Stuff to feed saveNamespaces()
939 $user = $this->getUser();
940 if ( $user->isLoggedIn() ) {
941 $remember .= Xml
::checkLabel(
942 wfMessage( 'powersearch-remember' )->text(),
944 'mw-search-powersearch-remember',
946 // The token goes here rather than in a hidden field so it
947 // is only sent when necessary (not every form submission).
948 array( 'value' => $user->getEditToken(
955 // Return final output
956 return Xml
::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
957 Xml
::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
958 Xml
::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
959 Xml
::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
960 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
961 implode( Xml
::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
963 Xml
::element( 'div', array( 'class' => 'divider' ), '', false ) .
965 Xml
::closeElement( 'fieldset' );
971 protected function getSearchProfiles() {
972 // Builds list of Search Types (profiles)
973 $nsAllSet = array_keys( SearchEngine
::searchableNamespaces() );
977 'message' => 'searchprofile-articles',
978 'tooltip' => 'searchprofile-articles-tooltip',
979 'namespaces' => SearchEngine
::defaultNamespaces(),
980 'namespace-messages' => SearchEngine
::namespacesAsText(
981 SearchEngine
::defaultNamespaces()
985 'message' => 'searchprofile-images',
986 'tooltip' => 'searchprofile-images-tooltip',
987 'namespaces' => array( NS_FILE
),
990 'message' => 'searchprofile-everything',
991 'tooltip' => 'searchprofile-everything-tooltip',
992 'namespaces' => $nsAllSet,
995 'message' => 'searchprofile-advanced',
996 'tooltip' => 'searchprofile-advanced-tooltip',
997 'namespaces' => self
::NAMESPACES_CURRENT
,
1001 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1003 foreach ( $profiles as &$data ) {
1004 if ( !is_array( $data['namespaces'] ) ) {
1007 sort( $data['namespaces'] );
1014 * @param string $term
1017 protected function formHeader( $term ) {
1018 $out = Xml
::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1021 if ( $this->startsWithImage( $term ) ) {
1023 $bareterm = substr( $term, strpos( $term, ':' ) +
1 );
1026 $profiles = $this->getSearchProfiles();
1027 $lang = $this->getLanguage();
1029 // Outputs XML for Search Types
1030 $out .= Xml
::openElement( 'div', array( 'class' => 'search-types' ) );
1031 $out .= Xml
::openElement( 'ul' );
1032 foreach ( $profiles as $id => $profile ) {
1033 if ( !isset( $profile['parameters'] ) ) {
1034 $profile['parameters'] = array();
1036 $profile['parameters']['profile'] = $id;
1038 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1039 $lang->commaList( $profile['namespace-messages'] ) : null;
1043 'class' => $this->profile
=== $id ?
'current' : 'normal'
1045 $this->makeSearchLink(
1048 $this->msg( $profile['message'] )->text(),
1049 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1050 $profile['parameters']
1054 $out .= Xml
::closeElement( 'ul' );
1055 $out .= Xml
::closeElement( 'div' );
1056 $out .= Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1057 $out .= Xml
::closeElement( 'div' );
1061 $opts['profile'] = $this->profile
;
1063 if ( $this->profile
=== 'advanced' ) {
1064 $out .= $this->powerSearchBox( $term, $opts );
1067 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile
, $term, $opts ) );
1075 * @param string $term
1076 * @param int $resultsShown
1077 * @param int $totalNum
1080 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1081 $out = Html
::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1082 $out .= Html
::hidden( 'profile', $this->profile
) . "\n";
1084 $out .= Html
::input( 'search', $term, 'search', array(
1085 'id' => $this->profile
=== 'advanced' ?
'powerSearchText' : 'searchText',
1088 'class' => 'mw-ui-input mw-ui-input-inline',
1090 $out .= Html
::hidden( 'fulltext', 'Search' ) . "\n";
1091 $out .= Xml
::submitButton(
1092 $this->msg( 'searchbutton' )->text(),
1093 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1097 if ( $totalNum > 0 && $this->offset
< $totalNum ) {
1098 $top = $this->msg( 'search-showingresults' )
1099 ->numParams( $this->offset +
1, $this->offset +
$resultsShown, $totalNum )
1100 ->numParams( $resultsShown )
1102 $out .= Xml
::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1103 Xml
::element( 'div', array( 'style' => 'clear:both' ), '', false );
1106 return $out . $this->didYouMeanHtml
;
1110 * Make a search link with some target namespaces
1112 * @param string $term
1113 * @param array $namespaces Ignored
1114 * @param string $label Link's text
1115 * @param string $tooltip Link's tooltip
1116 * @param array $params Query string parameters
1117 * @return string HTML fragment
1119 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1121 foreach ( $namespaces as $n ) {
1122 $opt['ns' . $n] = 1;
1125 $stParams = array_merge(
1128 'fulltext' => $this->msg( 'search' )->text()
1133 return Xml
::element(
1136 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1144 * Check if query starts with image: prefix
1146 * @param string $term The string to check
1149 protected function startsWithImage( $term ) {
1152 $parts = explode( ':', $term );
1153 if ( count( $parts ) > 1 ) {
1154 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE
;
1161 * Check if query starts with all: prefix
1163 * @param string $term The string to check
1166 protected function startsWithAll( $term ) {
1168 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1170 $parts = explode( ':', $term );
1171 if ( count( $parts ) > 1 ) {
1172 return $parts[0] == $allkeyword;
1181 * @return SearchEngine
1183 public function getSearchEngine() {
1184 if ( $this->searchEngine
=== null ) {
1185 $this->searchEngine
= $this->searchEngineType ?
1186 SearchEngine
::create( $this->searchEngineType
) : SearchEngine
::create();
1189 return $this->searchEngine
;
1193 * Current search profile.
1194 * @return null|string
1196 function getProfile() {
1197 return $this->profile
;
1201 * Current namespaces.
1204 function getNamespaces() {
1205 return $this->namespaces
;
1209 * Users of hook SpecialSearchSetupEngine can use this to
1210 * add more params to links to not lose selection when
1211 * user navigates search results.
1214 * @param string $key
1215 * @param mixed $value
1217 public function setExtraParam( $key, $value ) {
1218 $this->extraParams
[$key] = $value;
1221 protected function getGroupName() {