SpecialSearch: Simplify result info
[mediawiki.git] / includes / specials / SpecialSearch.php
blob5c3b3906504f49d0291e88eaa64af2161975cf11
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 $didYouMeanHtml, $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 ) );
88 // Strip underscores from title parameter; most of the time we'll want
89 // text form here. But don't strip underscores from actual text params!
90 $titleParam = str_replace( '_', ' ', $par );
92 $request = $this->getRequest();
94 // Fetch the search term
95 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
97 $this->load();
99 $this->searchEngineType = $request->getVal( 'srbackend' );
101 if ( $request->getVal( 'fulltext' )
102 || !is_null( $request->getVal( 'offset' ) )
104 $this->showResults( $search );
105 } else {
106 $this->goResult( $search );
111 * Set up basic search parameters from the request and user settings.
113 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
115 public function load() {
116 $request = $this->getRequest();
117 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20 );
118 $this->mPrefix = $request->getVal( 'prefix', '' );
120 $user = $this->getUser();
122 # Extract manually requested namespaces
123 $nslist = $this->powerSearch( $request );
124 if ( !count( $nslist ) ) {
125 # Fallback to user preference
126 $nslist = SearchEngine::userNamespaces( $user );
129 $profile = null;
130 if ( !count( $nslist ) ) {
131 $profile = 'default';
134 $profile = $request->getVal( 'profile', $profile );
135 $profiles = $this->getSearchProfiles();
136 if ( $profile === null ) {
137 // BC with old request format
138 $profile = 'advanced';
139 foreach ( $profiles as $key => $data ) {
140 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
141 $profile = $key;
144 $this->namespaces = $nslist;
145 } elseif ( $profile === 'advanced' ) {
146 $this->namespaces = $nslist;
147 } else {
148 if ( isset( $profiles[$profile]['namespaces'] ) ) {
149 $this->namespaces = $profiles[$profile]['namespaces'];
150 } else {
151 // Unknown profile requested
152 $profile = 'default';
153 $this->namespaces = $profiles['default']['namespaces'];
157 $this->didYouMeanHtml = ''; # html of did you mean... link
158 $this->fulltext = $request->getVal( 'fulltext' );
159 $this->profile = $profile;
163 * If an exact title match can be found, jump straight ahead to it.
165 * @param string $term
167 public function goResult( $term ) {
168 $this->setupPage( $term );
169 # Try to go to page as entered.
170 $title = Title::newFromText( $term );
171 # If the string cannot be used to create a title
172 if ( is_null( $title ) ) {
173 $this->showResults( $term );
175 return;
177 # If there's an exact or very near match, jump right there.
178 $title = SearchEngine::getNearMatch( $term );
180 if ( !is_null( $title ) ) {
181 $this->getOutput()->redirect( $title->getFullURL() );
183 return;
185 # No match, generate an edit URL
186 $title = Title::newFromText( $term );
187 if ( !is_null( $title ) ) {
188 global $wgGoToEdit;
189 wfRunHooks( 'SpecialSearchNogomatch', array( &$title ) );
190 wfDebugLog( 'nogomatch', $title->getFullText(), 'private' );
192 # If the feature is enabled, go straight to the edit page
193 if ( $wgGoToEdit ) {
194 $this->getOutput()->redirect( $title->getFullURL( array( 'action' => 'edit' ) ) );
196 return;
199 $this->showResults( $term );
203 * @param string $term
205 public function showResults( $term ) {
206 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
208 $profile = new ProfileSection( __METHOD__ );
209 $search = $this->getSearchEngine();
210 // Request an extra result to determine whether a "next page" link is useful
211 $search->setLimitOffset( $this->limit + 1, $this->offset );
212 $search->setNamespaces( $this->namespaces );
213 $this->saveNamespaces();
214 $search->prefix = $this->mPrefix;
215 $term = $search->transformSearchTerm( $term );
217 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
219 $this->setupPage( $term );
221 $out = $this->getOutput();
223 if ( $wgDisableTextSearch ) {
224 if ( $wgSearchForwardUrl ) {
225 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
226 $out->redirect( $url );
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 $this->didYouMeanHtml = '<div class="searchdidyoumean">'
292 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
295 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
296 # Hook requested termination
297 return;
300 // start rendering the page
301 $out->addHtml(
302 Xml::openElement(
303 'form',
304 array(
305 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
306 'method' => 'get',
307 'action' => $wgScript
312 // Get number of results
313 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
314 if ( $titleMatches ) {
315 $titleMatchesNum = $titleMatches->numRows();
316 $numTitleMatches = $titleMatches->getTotalHits();
318 if ( $textMatches ) {
319 $textMatchesNum = $textMatches->numRows();
320 $numTextMatches = $textMatches->getTotalHits();
322 $num = $titleMatchesNum + $textMatchesNum;
323 $totalRes = $numTitleMatches + $numTextMatches;
325 $out->addHtml(
326 # This is an awful awful ID name. It's not a table, but we
327 # named it poorly from when this was a table so now we're
328 # stuck with it
329 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
330 $this->shortDialog( $term, $num, $totalRes ) .
331 Xml::closeElement( 'div' ) .
332 $this->formHeader( $term ) .
333 Xml::closeElement( 'form' )
336 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
337 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
338 // Empty query -- straight view of search form
339 return;
342 $out->addHtml( "<div class='searchresults'>" );
344 // prev/next links
345 $prevnext = null;
346 if ( $num || $this->offset ) {
347 // Show the create link ahead
348 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
349 if ( $totalRes > $this->limit || $this->offset ) {
350 $prevnext = $this->getLanguage()->viewPrevNext(
351 $this->getPageTitle(),
352 $this->offset,
353 $this->limit,
354 $this->powerSearchOptions() + array( 'search' => $term ),
355 max( $titleMatchesNum, $textMatchesNum ) <= $this->limit
358 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
359 } else {
360 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
363 $out->parserOptions()->setEditSection( false );
364 if ( $titleMatches ) {
365 if ( $numTitleMatches > 0 ) {
366 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
367 $out->addHTML( $this->showMatches( $titleMatches ) );
369 $titleMatches->free();
371 if ( $textMatches && !$textStatus ) {
372 // output appropriate heading
373 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
374 // if no title matches the heading is redundant
375 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
378 // show interwiki results if any
379 if ( $textMatches->hasInterwikiResults() ) {
380 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
382 // show results
383 if ( $numTextMatches > 0 ) {
384 $out->addHTML( $this->showMatches( $textMatches ) );
387 $textMatches->free();
389 if ( $num === 0 ) {
390 if ( $textStatus ) {
391 $out->addHTML( '<div class="error">' .
392 $textStatus->getMessage( 'search-error' ) . '</div>' );
393 } else {
394 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
395 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
396 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
399 $out->addHtml( "</div>" );
401 if ( $prevnext ) {
402 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
407 * @param Title $title
408 * @param int $num The number of search results found
409 * @param null|SearchResultSet $titleMatches Results from title search
410 * @param null|SearchResultSet $textMatches Results from text search
412 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
413 // show direct page/create link if applicable
415 // Check DBkey !== '' in case of fragment link only.
416 if ( is_null( $title ) || $title->getDBkey() === ''
417 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
418 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
420 // invalid title
421 // preserve the paragraph for margins etc...
422 $this->getOutput()->addHtml( '<p></p>' );
424 return;
427 if ( $title->isKnown() ) {
428 $messageName = 'searchmenu-exists';
429 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
430 $messageName = 'searchmenu-new';
431 } else {
432 $messageName = 'searchmenu-new-nocreate';
434 $params = array(
435 $messageName,
436 wfEscapeWikiText( $title->getPrefixedText() ),
437 Message::numParam( $num )
439 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
441 // Extensions using the hook might still return an empty $messageName
442 if ( $messageName ) {
443 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
444 } else {
445 // preserve the paragraph for margins etc...
446 $this->getOutput()->addHtml( '<p></p>' );
451 * @param string $term
453 protected function setupPage( $term ) {
454 # Should advanced UI be used?
455 $this->searchAdvanced = ( $this->profile === 'advanced' );
456 $out = $this->getOutput();
457 if ( strval( $term ) !== '' ) {
458 $out->setPageTitle( $this->msg( 'searchresults' ) );
459 $out->setHTMLTitle( $this->msg( 'pagetitle' )
460 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
461 ->inContentLanguage()->text()
464 // add javascript specific to special:search
465 $out->addModules( 'mediawiki.special.search' );
469 * Extract "power search" namespace settings from the request object,
470 * returning a list of index numbers to search.
472 * @param WebRequest $request
473 * @return array
475 protected function powerSearch( &$request ) {
476 $arr = array();
477 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
478 if ( $request->getCheck( 'ns' . $ns ) ) {
479 $arr[] = $ns;
483 return $arr;
487 * Reconstruct the 'power search' options for links
489 * @return array
491 protected function powerSearchOptions() {
492 $opt = array();
493 if ( $this->profile !== 'advanced' ) {
494 $opt['profile'] = $this->profile;
495 } else {
496 foreach ( $this->namespaces as $n ) {
497 $opt['ns' . $n] = 1;
501 return $opt + $this->extraParams;
505 * Save namespace preferences when we're supposed to
507 * @return bool Whether we wrote something
509 protected function saveNamespaces() {
510 $user = $this->getUser();
511 $request = $this->getRequest();
513 if ( $user->isLoggedIn() &&
514 !is_null( $request->getVal( 'nsRemember' ) ) &&
515 $user->matchEditToken( $request->getVal( 'nsToken' ) )
517 // Reset namespace preferences: namespaces are not searched
518 // when they're not mentioned in the URL parameters.
519 foreach ( MWNamespace::getValidNamespaces() as $n ) {
520 $user->setOption( 'searchNs' . $n, false );
522 // The request parameters include all the namespaces we just searched.
523 // Even if they're the same as an existing profile, they're not eaten.
524 foreach ( $this->namespaces as $n ) {
525 $user->setOption( 'searchNs' . $n, true );
528 $user->saveSettings();
529 return true;
532 return false;
536 * Show whole set of results
538 * @param SearchResultSet $matches
540 * @return string
542 protected function showMatches( &$matches ) {
543 global $wgContLang;
545 $profile = new ProfileSection( __METHOD__ );
546 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
548 $out = "<ul class='mw-search-results'>\n";
549 $result = $matches->next();
550 $count = 0;
551 while ( $result && $count < $this->limit ) {
552 $out .= $this->showHit( $result, $terms );
553 $result = $matches->next();
554 $count++;
556 $out .= "</ul>\n";
558 // convert the whole thing to desired language variant
559 $out = $wgContLang->convert( $out );
561 return $out;
565 * Format a single hit result
567 * @param SearchResult $result
568 * @param array $terms Terms to highlight
570 * @return string
572 protected function showHit( $result, $terms ) {
573 $profile = new ProfileSection( __METHOD__ );
575 if ( $result->isBrokenTitle() ) {
576 return '';
579 $title = $result->getTitle();
581 $titleSnippet = $result->getTitleSnippet( $terms );
583 if ( $titleSnippet == '' ) {
584 $titleSnippet = null;
587 $link_t = clone $title;
589 wfRunHooks( 'ShowSearchHitTitle',
590 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
592 $link = Linker::linkKnown(
593 $link_t,
594 $titleSnippet
597 //If page content is not readable, just return the title.
598 //This is not quite safe, but better than showing excerpts from non-readable pages
599 //Note that hiding the entry entirely would screw up paging.
600 if ( !$title->userCan( 'read', $this->getUser() ) ) {
601 return "<li>{$link}</li>\n";
604 // If the page doesn't *exist*... our search index is out of date.
605 // The least confusing at this point is to drop the result.
606 // You may get less results, but... oh well. :P
607 if ( $result->isMissingRevision() ) {
608 return '';
611 // format redirects / relevant sections
612 $redirectTitle = $result->getRedirectTitle();
613 $redirectText = $result->getRedirectSnippet( $terms );
614 $sectionTitle = $result->getSectionTitle();
615 $sectionText = $result->getSectionSnippet( $terms );
616 $redirect = '';
618 if ( !is_null( $redirectTitle ) ) {
619 if ( $redirectText == '' ) {
620 $redirectText = null;
623 $redirect = "<span class='searchalttitle'>" .
624 $this->msg( 'search-redirect' )->rawParams(
625 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
626 "</span>";
629 $section = '';
631 if ( !is_null( $sectionTitle ) ) {
632 if ( $sectionText == '' ) {
633 $sectionText = null;
636 $section = "<span class='searchalttitle'>" .
637 $this->msg( 'search-section' )->rawParams(
638 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
639 "</span>";
642 // format text extract
643 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
645 $lang = $this->getLanguage();
647 // format score
648 if ( is_null( $result->getScore() ) ) {
649 // Search engine doesn't report scoring info
650 $score = '';
651 } else {
652 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
653 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
654 . ' - ';
657 // format description
658 $byteSize = $result->getByteSize();
659 $wordCount = $result->getWordCount();
660 $timestamp = $result->getTimestamp();
661 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
662 ->numParams( $wordCount )->escaped();
664 if ( $title->getNamespace() == NS_CATEGORY ) {
665 $cat = Category::newFromTitle( $title );
666 $size = $this->msg( 'search-result-category-size' )
667 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
668 ->escaped();
671 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
673 // link to related articles if supported
674 $related = '';
675 if ( $result->hasRelated() ) {
676 $stParams = array_merge(
677 $this->powerSearchOptions(),
678 array(
679 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
680 ':' . $title->getPrefixedText(),
681 'fulltext' => $this->msg( 'search' )->text()
685 $related = ' -- ' . Linker::linkKnown(
686 $this->getPageTitle(),
687 $this->msg( 'search-relatedarticle' )->text(),
688 array(),
689 $stParams
693 $fileMatch = '';
694 // Include a thumbnail for media files...
695 if ( $title->getNamespace() == NS_FILE ) {
696 $img = $result->getFile();
697 $img = $img ?: wfFindFile( $title );
698 if ( $result->isFileMatch() ) {
699 $fileMatch = "<span class='searchalttitle'>" .
700 $this->msg( 'search-file-match' )->escaped() . "</span>";
702 if ( $img ) {
703 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
704 if ( $thumb ) {
705 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
706 // Float doesn't seem to interact well with the bullets.
707 // Table messes up vertical alignment of the bullets.
708 // Bullets are therefore disabled (didn't look great anyway).
709 return "<li>" .
710 '<table class="searchResultImage">' .
711 '<tr>' .
712 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
713 $thumb->toHtml( array( 'desc-link' => true ) ) .
714 '</td>' .
715 '<td style="vertical-align: top;">' .
716 "{$link} {$fileMatch}" .
717 $extract .
718 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
719 '</td>' .
720 '</tr>' .
721 '</table>' .
722 "</li>\n";
727 $html = null;
729 if ( wfRunHooks( 'ShowSearchHit', array(
730 $this, $result, $terms,
731 &$link, &$redirect, &$section, &$extract,
732 &$score, &$size, &$date, &$related,
733 &$html
734 ) ) ) {
735 $html = "<li><div class='mw-search-result-heading'>" .
736 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
737 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
738 "</li>\n";
741 return $html;
745 * Show results from other wikis
747 * @param SearchResultSet|array $matches
748 * @param string $query
750 * @return string
752 protected function showInterwiki( $matches, $query ) {
753 global $wgContLang;
754 $profile = new ProfileSection( __METHOD__ );
756 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
757 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
758 $out .= "<ul class='mw-search-iwresults'>\n";
760 // work out custom project captions
761 $customCaptions = array();
762 // format per line <iwprefix>:<caption>
763 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
764 foreach ( $customLines as $line ) {
765 $parts = explode( ":", $line, 2 );
766 if ( count( $parts ) == 2 ) { // validate line
767 $customCaptions[$parts[0]] = $parts[1];
771 if ( !is_array( $matches ) ) {
772 $matches = array( $matches );
775 foreach ( $matches as $set ) {
776 $prev = null;
777 $result = $set->next();
778 while ( $result ) {
779 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
780 $prev = $result->getInterwikiPrefix();
781 $result = $set->next();
785 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
786 $out .= "</ul></div>\n";
788 // convert the whole thing to desired language variant
789 $out = $wgContLang->convert( $out );
791 return $out;
795 * Show single interwiki link
797 * @param SearchResult $result
798 * @param string $lastInterwiki
799 * @param string $query
800 * @param array $customCaptions iw prefix -> caption
802 * @return string
804 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
805 $profile = new ProfileSection( __METHOD__ );
807 if ( $result->isBrokenTitle() ) {
808 return '';
811 $title = $result->getTitle();
813 $titleSnippet = $result->getTitleSnippet();
815 if ( $titleSnippet == '' ) {
816 $titleSnippet = null;
819 $link = Linker::linkKnown(
820 $title,
821 $titleSnippet
824 // format redirect if any
825 $redirectTitle = $result->getRedirectTitle();
826 $redirectText = $result->getRedirectSnippet();
827 $redirect = '';
828 if ( !is_null( $redirectTitle ) ) {
829 if ( $redirectText == '' ) {
830 $redirectText = null;
833 $redirect = "<span class='searchalttitle'>" .
834 $this->msg( 'search-redirect' )->rawParams(
835 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
836 "</span>";
839 $out = "";
840 // display project name
841 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
842 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
843 // captions from 'search-interwiki-custom'
844 $caption = $customCaptions[$title->getInterwiki()];
845 } else {
846 // default is to show the hostname of the other wiki which might suck
847 // if there are many wikis on one hostname
848 $parsed = wfParseUrl( $title->getFullURL() );
849 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
851 // "more results" link (special page stuff could be localized, but we might not know target lang)
852 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
853 $searchLink = Linker::linkKnown(
854 $searchTitle,
855 $this->msg( 'search-interwiki-more' )->text(),
856 array(),
857 array(
858 'search' => $query,
859 'fulltext' => 'Search'
862 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
863 {$searchLink}</span>{$caption}</div>\n<ul>";
866 $out .= "<li>{$link} {$redirect}</li>\n";
868 return $out;
872 * Generates the power search box at [[Special:Search]]
874 * @param string $term Search term
875 * @param array $opts
876 * @return string HTML form
878 protected function powerSearchBox( $term, $opts ) {
879 global $wgContLang;
881 // Groups namespaces into rows according to subject
882 $rows = array();
883 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
884 $subject = MWNamespace::getSubject( $namespace );
885 if ( !array_key_exists( $subject, $rows ) ) {
886 $rows[$subject] = "";
889 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
890 if ( $name == '' ) {
891 $name = $this->msg( 'blanknamespace' )->text();
894 $rows[$subject] .=
895 Xml::openElement(
896 'td', array( 'style' => 'white-space: nowrap' )
898 Xml::checkLabel(
899 $name,
900 "ns{$namespace}",
901 "mw-search-ns{$namespace}",
902 in_array( $namespace, $this->namespaces )
904 Xml::closeElement( 'td' );
907 $rows = array_values( $rows );
908 $numRows = count( $rows );
910 // Lays out namespaces in multiple floating two-column tables so they'll
911 // be arranged nicely while still accommodating different screen widths
912 $namespaceTables = '';
913 for ( $i = 0; $i < $numRows; $i += 4 ) {
914 $namespaceTables .= Xml::openElement(
915 'table',
916 array( 'cellpadding' => 0, 'cellspacing' => 0 )
919 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
920 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
923 $namespaceTables .= Xml::closeElement( 'table' );
926 $showSections = array( 'namespaceTables' => $namespaceTables );
928 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
930 $hidden = '';
931 foreach ( $opts as $key => $value ) {
932 $hidden .= Html::hidden( $key, $value );
935 # Stuff to feed saveNamespaces()
936 $remember = '';
937 $user = $this->getUser();
938 if ( $user->isLoggedIn() ) {
939 $remember .= Html::hidden( 'nsToken', $user->getEditToken() ) .
940 Xml::checkLabel(
941 wfMessage( 'powersearch-remember' )->text(),
942 'nsRemember',
943 'mw-search-powersearch-remember',
944 false
948 // Return final output
949 return Xml::openElement(
950 'fieldset',
951 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
953 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
954 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
955 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
956 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
957 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
958 $hidden .
959 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
960 $remember .
961 Xml::closeElement( 'fieldset' );
965 * @return array
967 protected function getSearchProfiles() {
968 // Builds list of Search Types (profiles)
969 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
971 $profiles = array(
972 'default' => array(
973 'message' => 'searchprofile-articles',
974 'tooltip' => 'searchprofile-articles-tooltip',
975 'namespaces' => SearchEngine::defaultNamespaces(),
976 'namespace-messages' => SearchEngine::namespacesAsText(
977 SearchEngine::defaultNamespaces()
980 'images' => array(
981 'message' => 'searchprofile-images',
982 'tooltip' => 'searchprofile-images-tooltip',
983 'namespaces' => array( NS_FILE ),
985 'all' => array(
986 'message' => 'searchprofile-everything',
987 'tooltip' => 'searchprofile-everything-tooltip',
988 'namespaces' => $nsAllSet,
990 'advanced' => array(
991 'message' => 'searchprofile-advanced',
992 'tooltip' => 'searchprofile-advanced-tooltip',
993 'namespaces' => self::NAMESPACES_CURRENT,
997 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
999 foreach ( $profiles as &$data ) {
1000 if ( !is_array( $data['namespaces'] ) ) {
1001 continue;
1003 sort( $data['namespaces'] );
1006 return $profiles;
1010 * @param string $term
1011 * @return string
1013 protected function formHeader( $term ) {
1014 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1016 $bareterm = $term;
1017 if ( $this->startsWithImage( $term ) ) {
1018 // Deletes prefixes
1019 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1022 $profiles = $this->getSearchProfiles();
1023 $lang = $this->getLanguage();
1025 // Outputs XML for Search Types
1026 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1027 $out .= Xml::openElement( 'ul' );
1028 foreach ( $profiles as $id => $profile ) {
1029 if ( !isset( $profile['parameters'] ) ) {
1030 $profile['parameters'] = array();
1032 $profile['parameters']['profile'] = $id;
1034 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1035 $lang->commaList( $profile['namespace-messages'] ) : null;
1036 $out .= Xml::tags(
1037 'li',
1038 array(
1039 'class' => $this->profile === $id ? 'current' : 'normal'
1041 $this->makeSearchLink(
1042 $bareterm,
1043 array(),
1044 $this->msg( $profile['message'] )->text(),
1045 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1046 $profile['parameters']
1050 $out .= Xml::closeElement( 'ul' );
1051 $out .= Xml::closeElement( 'div' );
1052 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1053 $out .= Xml::closeElement( 'div' );
1055 // Hidden stuff
1056 $opts = array();
1057 $opts['profile'] = $this->profile;
1059 if ( $this->profile === 'advanced' ) {
1060 $out .= $this->powerSearchBox( $term, $opts );
1061 } else {
1062 $form = '';
1063 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1064 $out .= $form;
1067 return $out;
1071 * @param string $term
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->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1080 'size' => '50',
1081 'autofocus',
1082 'class' => 'mw-ui-input',
1083 ) ) . "\n";
1084 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1085 $out .= Xml::submitButton(
1086 $this->msg( 'searchbutton' )->text(),
1087 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1088 ) . "\n";
1090 // Results-info
1091 if ( $totalNum > 0 ) {
1092 $top = $this->msg( 'showingresultsheader' )
1093 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1094 ->params( wfEscapeWikiText( $term ) )
1095 ->numParams( $resultsShown )
1096 ->parse();
1097 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top );
1100 return $out . $this->didYouMeanHtml;
1104 * Make a search link with some target namespaces
1106 * @param string $term
1107 * @param array $namespaces Ignored
1108 * @param string $label Link's text
1109 * @param string $tooltip Link's tooltip
1110 * @param array $params Query string parameters
1111 * @return string HTML fragment
1113 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1114 $opt = $params;
1115 foreach ( $namespaces as $n ) {
1116 $opt['ns' . $n] = 1;
1119 $stParams = array_merge(
1120 array(
1121 'search' => $term,
1122 'fulltext' => $this->msg( 'search' )->text()
1124 $opt
1127 return Xml::element(
1128 'a',
1129 array(
1130 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1131 'title' => $tooltip
1133 $label
1138 * Check if query starts with image: prefix
1140 * @param string $term The string to check
1141 * @return bool
1143 protected function startsWithImage( $term ) {
1144 global $wgContLang;
1146 $parts = explode( ':', $term );
1147 if ( count( $parts ) > 1 ) {
1148 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1151 return false;
1155 * Check if query starts with all: prefix
1157 * @param string $term The string to check
1158 * @return bool
1160 protected function startsWithAll( $term ) {
1162 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1164 $parts = explode( ':', $term );
1165 if ( count( $parts ) > 1 ) {
1166 return $parts[0] == $allkeyword;
1169 return false;
1173 * @since 1.18
1175 * @return SearchEngine
1177 public function getSearchEngine() {
1178 if ( $this->searchEngine === null ) {
1179 $this->searchEngine = $this->searchEngineType ?
1180 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1183 return $this->searchEngine;
1187 * Current search profile.
1188 * @return null|string
1190 function getProfile() {
1191 return $this->profile;
1195 * Current namespaces.
1196 * @return array
1198 function getNamespaces() {
1199 return $this->namespaces;
1203 * Users of hook SpecialSearchSetupEngine can use this to
1204 * add more params to links to not lose selection when
1205 * user navigates search results.
1206 * @since 1.18
1208 * @param string $key
1209 * @param mixed $value
1211 public function setExtraParam( $key, $value ) {
1212 $this->extraParams[$key] = $value;
1215 protected function getGroupName() {
1216 return 'pages';