Implement extension registration from an extension.json file
[mediawiki.git] / includes / specials / SpecialSearch.php
blob55be2c2b34c5df92610d4e5af327d8839b47658d
1 <?php
2 /**
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
22 * @file
23 * @ingroup SpecialPage
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
30 class SpecialSearch extends SpecialPage {
31 /**
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.
37 * @var null|string
39 protected $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 */
51 protected $mPrefix;
53 /**
54 * @var int
56 protected $limit, $offset;
58 /**
59 * @var array
61 protected $namespaces;
63 /**
64 * @var string
66 protected $fulltext;
68 const NAMESPACES_CURRENT = 'sense';
70 public function __construct() {
71 parent::__construct( 'Search' );
74 /**
75 * Entry point
77 * @param string $par
79 public function execute( $par ) {
80 $this->setHeaders();
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',
86 'mediawiki.ui.input',
87 ) );
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 ) );
98 $this->load();
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 ) );
107 return;
110 $this->searchEngineType = $request->getVal( 'srbackend' );
112 if ( $request->getVal( 'fulltext' )
113 || !is_null( $request->getVal( 'offset' ) )
115 $this->showResults( $search );
116 } else {
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 );
140 $profile = null;
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' ) {
152 $profile = $key;
155 $this->namespaces = $nslist;
156 } elseif ( $profile === 'advanced' ) {
157 $this->namespaces = $nslist;
158 } else {
159 if ( isset( $profiles[$profile]['namespaces'] ) ) {
160 $this->namespaces = $profiles[$profile]['namespaces'];
161 } else {
162 // Unknown profile requested
163 $profile = 'default';
164 $this->namespaces = $profiles['default']['namespaces'];
168 $this->fulltext = $request->getVal( 'fulltext' );
169 $this->profile = $profile;
173 * If an exact title match can be found, jump straight ahead to it.
175 * @param string $term
177 public function goResult( $term ) {
178 $this->setupPage( $term );
179 # Try to go to page as entered.
180 $title = Title::newFromText( $term );
181 # If the string cannot be used to create a title
182 if ( is_null( $title ) ) {
183 $this->showResults( $term );
185 return;
187 # If there's an exact or very near match, jump right there.
188 $title = SearchEngine::getNearMatch( $term );
190 if ( !is_null( $title ) ) {
191 $this->getOutput()->redirect( $title->getFullURL() );
193 return;
195 # No match, generate an edit URL
196 $title = Title::newFromText( $term );
197 if ( !is_null( $title ) ) {
198 Hooks::run( 'SpecialSearchNogomatch', array( &$title ) );
200 $this->showResults( $term );
204 * @param string $term
206 public function showResults( $term ) {
207 global $wgContLang;
209 $search = $this->getSearchEngine();
210 $search->setLimitOffset( $this->limit, $this->offset );
211 $search->setNamespaces( $this->namespaces );
212 $search->prefix = $this->mPrefix;
213 $term = $search->transformSearchTerm( $term );
214 $didYouMeanHtml = '';
216 Hooks::run( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
218 $this->setupPage( $term );
220 $out = $this->getOutput();
222 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
223 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
224 if ( $searchFowardUrl ) {
225 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
226 $out->redirect( $url );
227 } else {
228 $out->addHTML(
229 Xml::openElement( 'fieldset' ) .
230 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
231 Xml::element(
232 'p',
233 array( 'class' => 'mw-searchdisabled' ),
234 $this->msg( 'searchdisabled' )->text()
236 $this->msg( 'googlesearch' )->rawParams(
237 htmlspecialchars( $term ),
238 'UTF-8',
239 $this->msg( 'searchbutton' )->escaped()
240 )->text() .
241 Xml::closeElement( 'fieldset' )
245 return;
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 );
258 $textStatus = null;
259 if ( $textMatches instanceof Status ) {
260 $textStatus = $textMatches;
261 $textMatches = null;
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(
274 $didYouMeanParams,
275 $this->powerSearchOptions()
278 $suggestionSnippet = $textMatches->getSuggestionSnippet();
280 if ( $suggestionSnippet == '' ) {
281 $suggestionSnippet = null;
284 $suggestLink = Linker::linkKnown(
285 $this->getPageTitle(),
286 $suggestionSnippet,
287 array(),
288 $stParams
291 # html of did you mean... search suggestion link
292 $didYouMeanHtml =
293 Xml::openElement( 'div', array( 'class' => 'searchdidyoumean' ) ) .
294 $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() .
295 Xml::closeElement( 'div' );
298 if ( !Hooks::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
299 # Hook requested termination
300 return;
303 // start rendering the page
304 $out->addHtml(
305 Xml::openElement(
306 'form',
307 array(
308 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
309 'method' => 'get',
310 'action' => wfScript(),
315 // Get number of results
316 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
317 if ( $titleMatches ) {
318 $titleMatchesNum = $titleMatches->numRows();
319 $numTitleMatches = $titleMatches->getTotalHits();
321 if ( $textMatches ) {
322 $textMatchesNum = $textMatches->numRows();
323 $numTextMatches = $textMatches->getTotalHits();
325 $num = $titleMatchesNum + $textMatchesNum;
326 $totalRes = $numTitleMatches + $numTextMatches;
328 $out->addHtml(
329 # This is an awful awful ID name. It's not a table, but we
330 # named it poorly from when this was a table so now we're
331 # stuck with it
332 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
333 $this->shortDialog( $term, $num, $totalRes ) .
334 Xml::closeElement( 'div' ) .
335 $this->searchProfileTabs( $term ) .
336 $this->searchOptions( $term ) .
337 Xml::closeElement( 'form' ) .
338 $didYouMeanHtml
341 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
342 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
343 // Empty query -- straight view of search form
344 return;
347 $out->addHtml( "<div class='searchresults'>" );
349 // prev/next links
350 $prevnext = null;
351 if ( $num || $this->offset ) {
352 // Show the create link ahead
353 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
354 if ( $totalRes > $this->limit || $this->offset ) {
355 if ( $this->searchEngineType !== null ) {
356 $this->setExtraParam( 'srbackend', $this->searchEngineType );
358 $prevnext = $this->getLanguage()->viewPrevNext(
359 $this->getPageTitle(),
360 $this->offset,
361 $this->limit,
362 $this->powerSearchOptions() + array( 'search' => $term ),
363 $this->limit + $this->offset >= $totalRes
367 Hooks::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
369 $out->parserOptions()->setEditSection( false );
370 if ( $titleMatches ) {
371 if ( $numTitleMatches > 0 ) {
372 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
373 $out->addHTML( $this->showMatches( $titleMatches ) );
375 $titleMatches->free();
377 if ( $textMatches && !$textStatus ) {
378 // output appropriate heading
379 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
380 // if no title matches the heading is redundant
381 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
384 // show interwiki results if any
385 if ( $textMatches->hasInterwikiResults() ) {
386 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
388 // show results
389 if ( $numTextMatches > 0 ) {
390 $out->addHTML( $this->showMatches( $textMatches ) );
393 $textMatches->free();
395 if ( $num === 0 ) {
396 if ( $textStatus ) {
397 $out->addHTML( '<div class="error">' .
398 $textStatus->getMessage( 'search-error' ) . '</div>' );
399 } else {
400 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
401 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
402 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
405 $out->addHtml( "</div>" );
407 if ( $prevnext ) {
408 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
413 * @param Title $title
414 * @param int $num The number of search results found
415 * @param null|SearchResultSet $titleMatches Results from title search
416 * @param null|SearchResultSet $textMatches Results from text search
418 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
419 // show direct page/create link if applicable
421 // Check DBkey !== '' in case of fragment link only.
422 if ( is_null( $title ) || $title->getDBkey() === ''
423 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
424 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
426 // invalid title
427 // preserve the paragraph for margins etc...
428 $this->getOutput()->addHtml( '<p></p>' );
430 return;
433 $messageName = 'searchmenu-new-nocreate';
434 $linkClass = 'mw-search-createlink';
436 if ( !$title->isExternal() ) {
437 if ( $title->isKnown() ) {
438 $messageName = 'searchmenu-exists';
439 $linkClass = 'mw-search-exists';
440 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
441 $messageName = 'searchmenu-new';
445 $params = array(
446 $messageName,
447 wfEscapeWikiText( $title->getPrefixedText() ),
448 Message::numParam( $num )
450 Hooks::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
452 // Extensions using the hook might still return an empty $messageName
453 if ( $messageName ) {
454 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
455 } else {
456 // preserve the paragraph for margins etc...
457 $this->getOutput()->addHtml( '<p></p>' );
462 * @param string $term
464 protected function setupPage( $term ) {
465 $out = $this->getOutput();
466 if ( strval( $term ) !== '' ) {
467 $out->setPageTitle( $this->msg( 'searchresults' ) );
468 $out->setHTMLTitle( $this->msg( 'pagetitle' )
469 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
470 ->inContentLanguage()->text()
473 // add javascript specific to special:search
474 $out->addModules( 'mediawiki.special.search' );
478 * Return true if current search is a power (advanced) search
480 * @return bool
482 protected function isPowerSearch() {
483 return $this->profile === 'advanced';
487 * Extract "power search" namespace settings from the request object,
488 * returning a list of index numbers to search.
490 * @param WebRequest $request
491 * @return array
493 protected function powerSearch( &$request ) {
494 $arr = array();
495 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
496 if ( $request->getCheck( 'ns' . $ns ) ) {
497 $arr[] = $ns;
501 return $arr;
505 * Reconstruct the 'power search' options for links
507 * @return array
509 protected function powerSearchOptions() {
510 $opt = array();
511 if ( !$this->isPowerSearch() ) {
512 $opt['profile'] = $this->profile;
513 } else {
514 foreach ( $this->namespaces as $n ) {
515 $opt['ns' . $n] = 1;
519 return $opt + $this->extraParams;
523 * Save namespace preferences when we're supposed to
525 * @return bool Whether we wrote something
527 protected function saveNamespaces() {
528 $user = $this->getUser();
529 $request = $this->getRequest();
531 if ( $user->isLoggedIn() &&
532 $user->matchEditToken(
533 $request->getVal( 'nsRemember' ),
534 'searchnamespace',
535 $request
538 // Reset namespace preferences: namespaces are not searched
539 // when they're not mentioned in the URL parameters.
540 foreach ( MWNamespace::getValidNamespaces() as $n ) {
541 $user->setOption( 'searchNs' . $n, false );
543 // The request parameters include all the namespaces to be searched.
544 // Even if they're the same as an existing profile, they're not eaten.
545 foreach ( $this->namespaces as $n ) {
546 $user->setOption( 'searchNs' . $n, true );
549 $user->saveSettings();
550 return true;
553 return false;
557 * Show whole set of results
559 * @param SearchResultSet $matches
561 * @return string
563 protected function showMatches( &$matches ) {
564 global $wgContLang;
566 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
568 $out = "<ul class='mw-search-results'>\n";
569 $result = $matches->next();
570 while ( $result ) {
571 $out .= $this->showHit( $result, $terms );
572 $result = $matches->next();
574 $out .= "</ul>\n";
576 // convert the whole thing to desired language variant
577 $out = $wgContLang->convert( $out );
579 return $out;
583 * Format a single hit result
585 * @param SearchResult $result
586 * @param array $terms Terms to highlight
588 * @return string
590 protected function showHit( $result, $terms ) {
592 if ( $result->isBrokenTitle() ) {
593 return '';
596 $title = $result->getTitle();
598 $titleSnippet = $result->getTitleSnippet();
600 if ( $titleSnippet == '' ) {
601 $titleSnippet = null;
604 $link_t = clone $title;
606 Hooks::run( 'ShowSearchHitTitle',
607 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
609 $link = Linker::linkKnown(
610 $link_t,
611 $titleSnippet
614 //If page content is not readable, just return the title.
615 //This is not quite safe, but better than showing excerpts from non-readable pages
616 //Note that hiding the entry entirely would screw up paging.
617 if ( !$title->userCan( 'read', $this->getUser() ) ) {
618 return "<li>{$link}</li>\n";
621 // If the page doesn't *exist*... our search index is out of date.
622 // The least confusing at this point is to drop the result.
623 // You may get less results, but... oh well. :P
624 if ( $result->isMissingRevision() ) {
625 return '';
628 // format redirects / relevant sections
629 $redirectTitle = $result->getRedirectTitle();
630 $redirectText = $result->getRedirectSnippet();
631 $sectionTitle = $result->getSectionTitle();
632 $sectionText = $result->getSectionSnippet();
633 $categorySnippet = $result->getCategorySnippet();
635 $redirect = '';
636 if ( !is_null( $redirectTitle ) ) {
637 if ( $redirectText == '' ) {
638 $redirectText = null;
641 $redirect = "<span class='searchalttitle'>" .
642 $this->msg( 'search-redirect' )->rawParams(
643 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
644 "</span>";
647 $section = '';
648 if ( !is_null( $sectionTitle ) ) {
649 if ( $sectionText == '' ) {
650 $sectionText = null;
653 $section = "<span class='searchalttitle'>" .
654 $this->msg( 'search-section' )->rawParams(
655 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
656 "</span>";
659 $category = '';
660 if ( $categorySnippet ) {
661 $category = "<span class='searchalttitle'>" .
662 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
663 "</span>";
666 // format text extract
667 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
669 $lang = $this->getLanguage();
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() )
682 ->escaped();
685 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
687 $fileMatch = '';
688 // Include a thumbnail for media files...
689 if ( $title->getNamespace() == NS_FILE ) {
690 $img = $result->getFile();
691 $img = $img ?: wfFindFile( $title );
692 if ( $result->isFileMatch() ) {
693 $fileMatch = "<span class='searchalttitle'>" .
694 $this->msg( 'search-file-match' )->escaped() . "</span>";
696 if ( $img ) {
697 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
698 if ( $thumb ) {
699 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
700 // Float doesn't seem to interact well with the bullets.
701 // Table messes up vertical alignment of the bullets.
702 // Bullets are therefore disabled (didn't look great anyway).
703 return "<li>" .
704 '<table class="searchResultImage">' .
705 '<tr>' .
706 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
707 $thumb->toHtml( array( 'desc-link' => true ) ) .
708 '</td>' .
709 '<td style="vertical-align: top;">' .
710 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
711 $extract .
712 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
713 '</td>' .
714 '</tr>' .
715 '</table>' .
716 "</li>\n";
721 $html = null;
723 $score = '';
724 if ( Hooks::run( 'ShowSearchHit', array(
725 $this, $result, $terms,
726 &$link, &$redirect, &$section, &$extract,
727 &$score, &$size, &$date, &$related,
728 &$html
729 ) ) ) {
730 $html = "<li><div class='mw-search-result-heading'>" .
731 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
732 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
733 "</li>\n";
736 return $html;
740 * Show results from other wikis
742 * @param SearchResultSet|array $matches
743 * @param string $query
745 * @return string
747 protected function showInterwiki( $matches, $query ) {
748 global $wgContLang;
750 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
751 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
752 $out .= "<ul class='mw-search-iwresults'>\n";
754 // work out custom project captions
755 $customCaptions = array();
756 // format per line <iwprefix>:<caption>
757 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
758 foreach ( $customLines as $line ) {
759 $parts = explode( ":", $line, 2 );
760 if ( count( $parts ) == 2 ) { // validate line
761 $customCaptions[$parts[0]] = $parts[1];
765 if ( !is_array( $matches ) ) {
766 $matches = array( $matches );
769 foreach ( $matches as $set ) {
770 $prev = null;
771 $result = $set->next();
772 while ( $result ) {
773 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
774 $prev = $result->getInterwikiPrefix();
775 $result = $set->next();
779 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
780 $out .= "</ul></div>\n";
782 // convert the whole thing to desired language variant
783 $out = $wgContLang->convert( $out );
785 return $out;
789 * Show single interwiki link
791 * @param SearchResult $result
792 * @param string $lastInterwiki
793 * @param string $query
794 * @param array $customCaptions Interwiki prefix -> caption
796 * @return string
798 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
800 if ( $result->isBrokenTitle() ) {
801 return '';
804 $title = $result->getTitle();
806 $titleSnippet = $result->getTitleSnippet();
808 if ( $titleSnippet == '' ) {
809 $titleSnippet = null;
812 $link = Linker::linkKnown(
813 $title,
814 $titleSnippet
817 // format redirect if any
818 $redirectTitle = $result->getRedirectTitle();
819 $redirectText = $result->getRedirectSnippet();
820 $redirect = '';
821 if ( !is_null( $redirectTitle ) ) {
822 if ( $redirectText == '' ) {
823 $redirectText = null;
826 $redirect = "<span class='searchalttitle'>" .
827 $this->msg( 'search-redirect' )->rawParams(
828 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
829 "</span>";
832 $out = "";
833 // display project name
834 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
835 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
836 // captions from 'search-interwiki-custom'
837 $caption = $customCaptions[$title->getInterwiki()];
838 } else {
839 // default is to show the hostname of the other wiki which might suck
840 // if there are many wikis on one hostname
841 $parsed = wfParseUrl( $title->getFullURL() );
842 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
844 // "more results" link (special page stuff could be localized, but we might not know target lang)
845 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
846 $searchLink = Linker::linkKnown(
847 $searchTitle,
848 $this->msg( 'search-interwiki-more' )->text(),
849 array(),
850 array(
851 'search' => $query,
852 'fulltext' => 'Search'
855 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
856 {$searchLink}</span>{$caption}</div>\n<ul>";
859 $out .= "<li>{$link} {$redirect}</li>\n";
861 return $out;
865 * Generates the power search box at [[Special:Search]]
867 * @param string $term Search term
868 * @param array $opts
869 * @return string HTML form
871 protected function powerSearchBox( $term, $opts ) {
872 global $wgContLang;
874 // Groups namespaces into rows according to subject
875 $rows = array();
876 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
877 $subject = MWNamespace::getSubject( $namespace );
878 if ( !array_key_exists( $subject, $rows ) ) {
879 $rows[$subject] = "";
882 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
883 if ( $name == '' ) {
884 $name = $this->msg( 'blanknamespace' )->text();
887 $rows[$subject] .=
888 Xml::openElement( 'td' ) .
889 Xml::checkLabel(
890 $name,
891 "ns{$namespace}",
892 "mw-search-ns{$namespace}",
893 in_array( $namespace, $this->namespaces )
895 Xml::closeElement( 'td' );
898 $rows = array_values( $rows );
899 $numRows = count( $rows );
901 // Lays out namespaces in multiple floating two-column tables so they'll
902 // be arranged nicely while still accommodating different screen widths
903 $namespaceTables = '';
904 for ( $i = 0; $i < $numRows; $i += 4 ) {
905 $namespaceTables .= Xml::openElement( 'table' );
907 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
908 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
911 $namespaceTables .= Xml::closeElement( 'table' );
914 $showSections = array( 'namespaceTables' => $namespaceTables );
916 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
918 $hidden = '';
919 foreach ( $opts as $key => $value ) {
920 $hidden .= Html::hidden( $key, $value );
923 # Stuff to feed saveNamespaces()
924 $remember = '';
925 $user = $this->getUser();
926 if ( $user->isLoggedIn() ) {
927 $remember .= Xml::checkLabel(
928 $this->msg( 'powersearch-remember' )->text(),
929 'nsRemember',
930 'mw-search-powersearch-remember',
931 false,
932 // The token goes here rather than in a hidden field so it
933 // is only sent when necessary (not every form submission).
934 array( 'value' => $user->getEditToken(
935 'searchnamespace',
936 $this->getRequest()
941 // Return final output
942 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
943 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
944 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
945 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
946 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
947 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
948 $hidden .
949 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
950 $remember .
951 Xml::closeElement( 'fieldset' );
955 * @return array
957 protected function getSearchProfiles() {
958 // Builds list of Search Types (profiles)
959 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
961 $profiles = array(
962 'default' => array(
963 'message' => 'searchprofile-articles',
964 'tooltip' => 'searchprofile-articles-tooltip',
965 'namespaces' => SearchEngine::defaultNamespaces(),
966 'namespace-messages' => SearchEngine::namespacesAsText(
967 SearchEngine::defaultNamespaces()
970 'images' => array(
971 'message' => 'searchprofile-images',
972 'tooltip' => 'searchprofile-images-tooltip',
973 'namespaces' => array( NS_FILE ),
975 'all' => array(
976 'message' => 'searchprofile-everything',
977 'tooltip' => 'searchprofile-everything-tooltip',
978 'namespaces' => $nsAllSet,
980 'advanced' => array(
981 'message' => 'searchprofile-advanced',
982 'tooltip' => 'searchprofile-advanced-tooltip',
983 'namespaces' => self::NAMESPACES_CURRENT,
987 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
989 foreach ( $profiles as &$data ) {
990 if ( !is_array( $data['namespaces'] ) ) {
991 continue;
993 sort( $data['namespaces'] );
996 return $profiles;
1000 * @param string $term
1001 * @return string
1003 protected function searchProfileTabs( $term ) {
1004 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1006 $bareterm = $term;
1007 if ( $this->startsWithImage( $term ) ) {
1008 // Deletes prefixes
1009 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1012 $profiles = $this->getSearchProfiles();
1013 $lang = $this->getLanguage();
1015 // Outputs XML for Search Types
1016 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1017 $out .= Xml::openElement( 'ul' );
1018 foreach ( $profiles as $id => $profile ) {
1019 if ( !isset( $profile['parameters'] ) ) {
1020 $profile['parameters'] = array();
1022 $profile['parameters']['profile'] = $id;
1024 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1025 $lang->commaList( $profile['namespace-messages'] ) : null;
1026 $out .= Xml::tags(
1027 'li',
1028 array(
1029 'class' => $this->profile === $id ? 'current' : 'normal'
1031 $this->makeSearchLink(
1032 $bareterm,
1033 array(),
1034 $this->msg( $profile['message'] )->text(),
1035 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1036 $profile['parameters']
1040 $out .= Xml::closeElement( 'ul' );
1041 $out .= Xml::closeElement( 'div' );
1042 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1043 $out .= Xml::closeElement( 'div' );
1045 return $out;
1049 * @param string $term Search term
1050 * @return string
1052 protected function searchOptions( $term ) {
1053 $out = '';
1054 $opts = array();
1055 $opts['profile'] = $this->profile;
1057 if ( $this->isPowerSearch() ) {
1058 $out .= $this->powerSearchBox( $term, $opts );
1059 } else {
1060 $form = '';
1061 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1062 $out .= $form;
1065 return $out;
1069 * @param string $term
1070 * @param int $resultsShown
1071 * @param int $totalNum
1072 * @return string
1074 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1075 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1076 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1077 // Term box
1078 $out .= Html::input( 'search', $term, 'search', array(
1079 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1080 'size' => '50',
1081 'autofocus' => trim( $term ) === '',
1082 'class' => 'mw-ui-input mw-ui-input-inline',
1083 ) ) . "\n";
1084 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1085 $out .= Html::submitButton(
1086 $this->msg( 'searchbutton' )->text(),
1087 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1088 array( 'mw-ui-progressive' )
1089 ) . "\n";
1091 // Results-info
1092 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1093 $top = $this->msg( 'search-showingresults' )
1094 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1095 ->numParams( $resultsShown )
1096 ->parse();
1097 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1098 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1101 return $out;
1105 * Make a search link with some target namespaces
1107 * @param string $term
1108 * @param array $namespaces Ignored
1109 * @param string $label Link's text
1110 * @param string $tooltip Link's tooltip
1111 * @param array $params Query string parameters
1112 * @return string HTML fragment
1114 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1115 $opt = $params;
1116 foreach ( $namespaces as $n ) {
1117 $opt['ns' . $n] = 1;
1120 $stParams = array_merge(
1121 array(
1122 'search' => $term,
1123 'fulltext' => $this->msg( 'search' )->text()
1125 $opt
1128 return Xml::element(
1129 'a',
1130 array(
1131 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1132 'title' => $tooltip
1134 $label
1139 * Check if query starts with image: prefix
1141 * @param string $term The string to check
1142 * @return bool
1144 protected function startsWithImage( $term ) {
1145 global $wgContLang;
1147 $parts = explode( ':', $term );
1148 if ( count( $parts ) > 1 ) {
1149 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1152 return false;
1156 * Check if query starts with all: prefix
1158 * @param string $term The string to check
1159 * @return bool
1161 protected function startsWithAll( $term ) {
1163 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1165 $parts = explode( ':', $term );
1166 if ( count( $parts ) > 1 ) {
1167 return $parts[0] == $allkeyword;
1170 return false;
1174 * @since 1.18
1176 * @return SearchEngine
1178 public function getSearchEngine() {
1179 if ( $this->searchEngine === null ) {
1180 $this->searchEngine = $this->searchEngineType ?
1181 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1184 return $this->searchEngine;
1188 * Current search profile.
1189 * @return null|string
1191 function getProfile() {
1192 return $this->profile;
1196 * Current namespaces.
1197 * @return array
1199 function getNamespaces() {
1200 return $this->namespaces;
1204 * Users of hook SpecialSearchSetupEngine can use this to
1205 * add more params to links to not lose selection when
1206 * user navigates search results.
1207 * @since 1.18
1209 * @param string $key
1210 * @param mixed $value
1212 public function setExtraParam( $key, $value ) {
1213 $this->extraParams[$key] = $value;
1216 protected function getGroupName() {
1217 return 'pages';