Actually format search error Status objects nicely
[mediawiki.git] / includes / specials / SpecialSearch.php
blob1cc5930ac7a4d839ef7e0d29b8cff853328a0576
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 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
257 $textMatches = $search->searchText( $rewritten );
260 $textStatus = null;
261 if ( $textMatches instanceof Status ) {
262 $textStatus = $textMatches;
263 $textMatches = null;
266 // did you mean... suggestions
267 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
268 # mirror Go/Search behavior of original request ..
269 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
271 if ( $this->fulltext != null ) {
272 $didYouMeanParams['fulltext'] = $this->fulltext;
275 $stParams = array_merge(
276 $didYouMeanParams,
277 $this->powerSearchOptions()
280 $suggestionSnippet = $textMatches->getSuggestionSnippet();
282 if ( $suggestionSnippet == '' ) {
283 $suggestionSnippet = null;
286 $suggestLink = Linker::linkKnown(
287 $this->getPageTitle(),
288 $suggestionSnippet,
289 array(),
290 $stParams
293 $this->didYouMeanHtml = '<div class="searchdidyoumean">'
294 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
297 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
298 # Hook requested termination
299 return;
302 // start rendering the page
303 $out->addHtml(
304 Xml::openElement(
305 'form',
306 array(
307 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
308 'method' => 'get',
309 'action' => $wgScript
313 $out->addHtml(
314 # This is an awful awful ID name. It's not a table, but we
315 # named it poorly from when this was a table so now we're
316 # stuck with it
317 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
318 $this->shortDialog( $term ) .
319 Xml::closeElement( 'div' )
322 // Sometimes the search engine knows there are too many hits
323 if ( $titleMatches instanceof SearchResultTooMany ) {
324 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
326 return;
329 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
330 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
331 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
332 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
333 $out->addHTML( '</form>' );
335 // Empty query -- straight view of search form
336 return;
339 // Get number of results
340 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
341 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
342 // Total initial query matches (possible false positives)
343 $num = $titleMatchesNum + $textMatchesNum;
345 // Get total actual results (after second filtering, if any)
346 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
347 $titleMatches->getTotalHits() : $titleMatchesNum;
348 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
349 $textMatches->getTotalHits() : $textMatchesNum;
351 // get total number of results if backend can calculate it
352 $totalRes = 0;
353 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
354 $totalRes += $titleMatches->getTotalHits();
356 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
357 $totalRes += $textMatches->getTotalHits();
360 // show number of results and current offset
361 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
362 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
364 $out->addHtml( Xml::closeElement( 'form' ) );
365 $out->addHtml( "<div class='searchresults'>" );
367 // prev/next links
368 $prevnext = null;
369 if ( $num || $this->offset ) {
370 // Show the create link ahead
371 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
372 if ( $totalRes > $this->limit || $this->offset ) {
373 $prevnext = $this->getLanguage()->viewPrevNext(
374 $this->getPageTitle(),
375 $this->offset,
376 $this->limit,
377 $this->powerSearchOptions() + array( 'search' => $term ),
378 max( $titleMatchesNum, $textMatchesNum ) <= $this->limit
381 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
382 } else {
383 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
386 $out->parserOptions()->setEditSection( false );
387 if ( $titleMatches ) {
388 if ( $numTitleMatches > 0 ) {
389 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
390 $out->addHTML( $this->showMatches( $titleMatches ) );
392 $titleMatches->free();
394 if ( $textMatches && !$textStatus ) {
395 // output appropriate heading
396 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
397 // if no title matches the heading is redundant
398 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
401 // show interwiki results if any
402 if ( $textMatches->hasInterwikiResults() ) {
403 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
405 // show results
406 if ( $numTextMatches > 0 ) {
407 $out->addHTML( $this->showMatches( $textMatches ) );
410 $textMatches->free();
412 if ( $num === 0 ) {
413 if ( $textStatus ) {
414 $out->addHTML( '<div class="error">' .
415 $textStatus->getMessage( 'search-error' ) . '</div>' );
416 } else {
417 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
418 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
419 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
422 $out->addHtml( "</div>" );
424 if ( $prevnext ) {
425 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
430 * @param Title $title
431 * @param int $num The number of search results found
432 * @param null|SearchResultSet $titleMatches Results from title search
433 * @param null|SearchResultSet $textMatches Results from text search
435 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
436 // show direct page/create link if applicable
438 // Check DBkey !== '' in case of fragment link only.
439 if ( is_null( $title ) || $title->getDBkey() === ''
440 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
441 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
443 // invalid title
444 // preserve the paragraph for margins etc...
445 $this->getOutput()->addHtml( '<p></p>' );
447 return;
450 if ( $title->isKnown() ) {
451 $messageName = 'searchmenu-exists';
452 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
453 $messageName = 'searchmenu-new';
454 } else {
455 $messageName = 'searchmenu-new-nocreate';
457 $params = array(
458 $messageName,
459 wfEscapeWikiText( $title->getPrefixedText() ),
460 Message::numParam( $num )
462 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
464 // Extensions using the hook might still return an empty $messageName
465 if ( $messageName ) {
466 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
467 } else {
468 // preserve the paragraph for margins etc...
469 $this->getOutput()->addHtml( '<p></p>' );
474 * @param string $term
476 protected function setupPage( $term ) {
477 # Should advanced UI be used?
478 $this->searchAdvanced = ( $this->profile === 'advanced' );
479 $out = $this->getOutput();
480 if ( strval( $term ) !== '' ) {
481 $out->setPageTitle( $this->msg( 'searchresults' ) );
482 $out->setHTMLTitle( $this->msg( 'pagetitle' )
483 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
484 ->inContentLanguage()->text()
487 // add javascript specific to special:search
488 $out->addModules( 'mediawiki.special.search' );
492 * Extract "power search" namespace settings from the request object,
493 * returning a list of index numbers to search.
495 * @param WebRequest $request
496 * @return array
498 protected function powerSearch( &$request ) {
499 $arr = array();
500 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
501 if ( $request->getCheck( 'ns' . $ns ) ) {
502 $arr[] = $ns;
506 return $arr;
510 * Reconstruct the 'power search' options for links
512 * @return array
514 protected function powerSearchOptions() {
515 $opt = array();
516 if ( $this->profile !== 'advanced' ) {
517 $opt['profile'] = $this->profile;
518 } else {
519 foreach ( $this->namespaces as $n ) {
520 $opt['ns' . $n] = 1;
524 return $opt + $this->extraParams;
528 * Save namespace preferences when we're supposed to
530 * @return bool Whether we wrote something
532 protected function saveNamespaces() {
533 $user = $this->getUser();
534 $request = $this->getRequest();
536 if ( $user->isLoggedIn() &&
537 !is_null( $request->getVal( 'nsRemember' ) ) &&
538 $user->matchEditToken( $request->getVal( 'nsToken' ) )
540 // Reset namespace preferences: namespaces are not searched
541 // when they're not mentioned in the URL parameters.
542 foreach ( MWNamespace::getValidNamespaces() as $n ) {
543 $user->setOption( 'searchNs' . $n, false );
545 // The request parameters include all the namespaces we just searched.
546 // Even if they're the same as an existing profile, they're not eaten.
547 foreach ( $this->namespaces as $n ) {
548 $user->setOption( 'searchNs' . $n, true );
551 $user->saveSettings();
552 return true;
555 return false;
559 * Show whole set of results
561 * @param SearchResultSet $matches
563 * @return string
565 protected function showMatches( &$matches ) {
566 global $wgContLang;
568 $profile = new ProfileSection( __METHOD__ );
569 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
571 $out = "<ul class='mw-search-results'>\n";
572 $result = $matches->next();
573 $count = 0;
574 while ( $result && $count < $this->limit ) {
575 $out .= $this->showHit( $result, $terms );
576 $result = $matches->next();
577 $count++;
579 $out .= "</ul>\n";
581 // convert the whole thing to desired language variant
582 $out = $wgContLang->convert( $out );
584 return $out;
588 * Format a single hit result
590 * @param SearchResult $result
591 * @param array $terms Terms to highlight
593 * @return string
595 protected function showHit( $result, $terms ) {
596 $profile = new ProfileSection( __METHOD__ );
598 if ( $result->isBrokenTitle() ) {
599 return '';
602 $title = $result->getTitle();
604 $titleSnippet = $result->getTitleSnippet( $terms );
606 if ( $titleSnippet == '' ) {
607 $titleSnippet = null;
610 $link_t = clone $title;
612 wfRunHooks( 'ShowSearchHitTitle',
613 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
615 $link = Linker::linkKnown(
616 $link_t,
617 $titleSnippet
620 //If page content is not readable, just return the title.
621 //This is not quite safe, but better than showing excerpts from non-readable pages
622 //Note that hiding the entry entirely would screw up paging.
623 if ( !$title->userCan( 'read', $this->getUser() ) ) {
624 return "<li>{$link}</li>\n";
627 // If the page doesn't *exist*... our search index is out of date.
628 // The least confusing at this point is to drop the result.
629 // You may get less results, but... oh well. :P
630 if ( $result->isMissingRevision() ) {
631 return '';
634 // format redirects / relevant sections
635 $redirectTitle = $result->getRedirectTitle();
636 $redirectText = $result->getRedirectSnippet( $terms );
637 $sectionTitle = $result->getSectionTitle();
638 $sectionText = $result->getSectionSnippet( $terms );
639 $redirect = '';
641 if ( !is_null( $redirectTitle ) ) {
642 if ( $redirectText == '' ) {
643 $redirectText = null;
646 $redirect = "<span class='searchalttitle'>" .
647 $this->msg( 'search-redirect' )->rawParams(
648 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
649 "</span>";
652 $section = '';
654 if ( !is_null( $sectionTitle ) ) {
655 if ( $sectionText == '' ) {
656 $sectionText = null;
659 $section = "<span class='searchalttitle'>" .
660 $this->msg( 'search-section' )->rawParams(
661 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
662 "</span>";
665 // format text extract
666 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
668 $lang = $this->getLanguage();
670 // format score
671 if ( is_null( $result->getScore() ) ) {
672 // Search engine doesn't report scoring info
673 $score = '';
674 } else {
675 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
676 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
677 . ' - ';
680 // format description
681 $byteSize = $result->getByteSize();
682 $wordCount = $result->getWordCount();
683 $timestamp = $result->getTimestamp();
684 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
685 ->numParams( $wordCount )->escaped();
687 if ( $title->getNamespace() == NS_CATEGORY ) {
688 $cat = Category::newFromTitle( $title );
689 $size = $this->msg( 'search-result-category-size' )
690 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
691 ->escaped();
694 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
696 // link to related articles if supported
697 $related = '';
698 if ( $result->hasRelated() ) {
699 $stParams = array_merge(
700 $this->powerSearchOptions(),
701 array(
702 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
703 ':' . $title->getPrefixedText(),
704 'fulltext' => $this->msg( 'search' )->text()
708 $related = ' -- ' . Linker::linkKnown(
709 $this->getPageTitle(),
710 $this->msg( 'search-relatedarticle' )->text(),
711 array(),
712 $stParams
716 $fileMatch = '';
717 // Include a thumbnail for media files...
718 if ( $title->getNamespace() == NS_FILE ) {
719 $img = $result->getFile();
720 $img = $img ?: wfFindFile( $title );
721 if ( $result->isFileMatch() ) {
722 $fileMatch = "<span class='searchalttitle'>" .
723 $this->msg( 'search-file-match' )->escaped() . "</span>";
725 if ( $img ) {
726 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
727 if ( $thumb ) {
728 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
729 // Float doesn't seem to interact well with the bullets.
730 // Table messes up vertical alignment of the bullets.
731 // Bullets are therefore disabled (didn't look great anyway).
732 return "<li>" .
733 '<table class="searchResultImage">' .
734 '<tr>' .
735 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
736 $thumb->toHtml( array( 'desc-link' => true ) ) .
737 '</td>' .
738 '<td style="vertical-align: top;">' .
739 "{$link} {$fileMatch}" .
740 $extract .
741 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
742 '</td>' .
743 '</tr>' .
744 '</table>' .
745 "</li>\n";
750 $html = null;
752 if ( wfRunHooks( 'ShowSearchHit', array(
753 $this, $result, $terms,
754 &$link, &$redirect, &$section, &$extract,
755 &$score, &$size, &$date, &$related,
756 &$html
757 ) ) ) {
758 $html = "<li><div class='mw-search-result-heading'>" .
759 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
760 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
761 "</li>\n";
764 return $html;
768 * Show results from other wikis
770 * @param SearchResultSet|array $matches
771 * @param string $query
773 * @return string
775 protected function showInterwiki( $matches, $query ) {
776 global $wgContLang;
777 $profile = new ProfileSection( __METHOD__ );
779 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
780 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
781 $out .= "<ul class='mw-search-iwresults'>\n";
783 // work out custom project captions
784 $customCaptions = array();
785 // format per line <iwprefix>:<caption>
786 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
787 foreach ( $customLines as $line ) {
788 $parts = explode( ":", $line, 2 );
789 if ( count( $parts ) == 2 ) { // validate line
790 $customCaptions[$parts[0]] = $parts[1];
794 if ( !is_array( $matches ) ) {
795 $matches = array( $matches );
798 foreach ( $matches as $set ) {
799 $prev = null;
800 $result = $set->next();
801 while ( $result ) {
802 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
803 $prev = $result->getInterwikiPrefix();
804 $result = $set->next();
808 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
809 $out .= "</ul></div>\n";
811 // convert the whole thing to desired language variant
812 $out = $wgContLang->convert( $out );
814 return $out;
818 * Show single interwiki link
820 * @param SearchResult $result
821 * @param string $lastInterwiki
822 * @param string $query
823 * @param array $customCaptions iw prefix -> caption
825 * @return string
827 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
828 $profile = new ProfileSection( __METHOD__ );
830 if ( $result->isBrokenTitle() ) {
831 return '';
834 $title = $result->getTitle();
836 $titleSnippet = $result->getTitleSnippet();
838 if ( $titleSnippet == '' ) {
839 $titleSnippet = null;
842 $link = Linker::linkKnown(
843 $title,
844 $titleSnippet
847 // format redirect if any
848 $redirectTitle = $result->getRedirectTitle();
849 $redirectText = $result->getRedirectSnippet();
850 $redirect = '';
851 if ( !is_null( $redirectTitle ) ) {
852 if ( $redirectText == '' ) {
853 $redirectText = null;
856 $redirect = "<span class='searchalttitle'>" .
857 $this->msg( 'search-redirect' )->rawParams(
858 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
859 "</span>";
862 $out = "";
863 // display project name
864 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
865 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
866 // captions from 'search-interwiki-custom'
867 $caption = $customCaptions[$title->getInterwiki()];
868 } else {
869 // default is to show the hostname of the other wiki which might suck
870 // if there are many wikis on one hostname
871 $parsed = wfParseUrl( $title->getFullURL() );
872 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
874 // "more results" link (special page stuff could be localized, but we might not know target lang)
875 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
876 $searchLink = Linker::linkKnown(
877 $searchTitle,
878 $this->msg( 'search-interwiki-more' )->text(),
879 array(),
880 array(
881 'search' => $query,
882 'fulltext' => 'Search'
885 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
886 {$searchLink}</span>{$caption}</div>\n<ul>";
889 $out .= "<li>{$link} {$redirect}</li>\n";
891 return $out;
895 * @param string $profile
896 * @param string $term
897 * @return string
899 protected function getProfileForm( $profile, $term ) {
900 // Hidden stuff
901 $opts = array();
902 $opts['profile'] = $this->profile;
904 if ( $profile === 'advanced' ) {
905 return $this->powerSearchBox( $term, $opts );
906 } else {
907 $form = '';
908 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
910 return $form;
915 * Generates the power search box at [[Special:Search]]
917 * @param string $term Search term
918 * @param array $opts
919 * @return string HTML form
921 protected function powerSearchBox( $term, $opts ) {
922 global $wgContLang;
924 // Groups namespaces into rows according to subject
925 $rows = array();
926 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
927 $subject = MWNamespace::getSubject( $namespace );
928 if ( !array_key_exists( $subject, $rows ) ) {
929 $rows[$subject] = "";
932 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
933 if ( $name == '' ) {
934 $name = $this->msg( 'blanknamespace' )->text();
937 $rows[$subject] .=
938 Xml::openElement(
939 'td', array( 'style' => 'white-space: nowrap' )
941 Xml::checkLabel(
942 $name,
943 "ns{$namespace}",
944 "mw-search-ns{$namespace}",
945 in_array( $namespace, $this->namespaces )
947 Xml::closeElement( 'td' );
950 $rows = array_values( $rows );
951 $numRows = count( $rows );
953 // Lays out namespaces in multiple floating two-column tables so they'll
954 // be arranged nicely while still accommodating different screen widths
955 $namespaceTables = '';
956 for ( $i = 0; $i < $numRows; $i += 4 ) {
957 $namespaceTables .= Xml::openElement(
958 'table',
959 array( 'cellpadding' => 0, 'cellspacing' => 0 )
962 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
963 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
966 $namespaceTables .= Xml::closeElement( 'table' );
969 $showSections = array( 'namespaceTables' => $namespaceTables );
971 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
973 $hidden = '';
974 foreach ( $opts as $key => $value ) {
975 $hidden .= Html::hidden( $key, $value );
978 # Stuff to feed saveNamespaces()
979 $remember = '';
980 $user = $this->getUser();
981 if ( $user->isLoggedIn() ) {
982 $remember .= Html::hidden( 'nsToken', $user->getEditToken() ) .
983 Xml::checkLabel(
984 wfMessage( 'powersearch-remember' )->text(),
985 'nsRemember',
986 'mw-search-powersearch-remember',
987 false
991 // Return final output
992 return Xml::openElement(
993 'fieldset',
994 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
996 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
997 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
998 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
999 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1000 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1001 $hidden .
1002 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1003 $remember .
1004 Xml::closeElement( 'fieldset' );
1008 * @return array
1010 protected function getSearchProfiles() {
1011 // Builds list of Search Types (profiles)
1012 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1014 $profiles = array(
1015 'default' => array(
1016 'message' => 'searchprofile-articles',
1017 'tooltip' => 'searchprofile-articles-tooltip',
1018 'namespaces' => SearchEngine::defaultNamespaces(),
1019 'namespace-messages' => SearchEngine::namespacesAsText(
1020 SearchEngine::defaultNamespaces()
1023 'images' => array(
1024 'message' => 'searchprofile-images',
1025 'tooltip' => 'searchprofile-images-tooltip',
1026 'namespaces' => array( NS_FILE ),
1028 'all' => array(
1029 'message' => 'searchprofile-everything',
1030 'tooltip' => 'searchprofile-everything-tooltip',
1031 'namespaces' => $nsAllSet,
1033 'advanced' => array(
1034 'message' => 'searchprofile-advanced',
1035 'tooltip' => 'searchprofile-advanced-tooltip',
1036 'namespaces' => self::NAMESPACES_CURRENT,
1040 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1042 foreach ( $profiles as &$data ) {
1043 if ( !is_array( $data['namespaces'] ) ) {
1044 continue;
1046 sort( $data['namespaces'] );
1049 return $profiles;
1053 * @param string $term
1054 * @param int $resultsShown
1055 * @param int $totalNum
1056 * @return string
1058 protected function formHeader( $term, $resultsShown, $totalNum ) {
1059 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1061 $bareterm = $term;
1062 if ( $this->startsWithImage( $term ) ) {
1063 // Deletes prefixes
1064 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1067 $profiles = $this->getSearchProfiles();
1068 $lang = $this->getLanguage();
1070 // Outputs XML for Search Types
1071 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1072 $out .= Xml::openElement( 'ul' );
1073 foreach ( $profiles as $id => $profile ) {
1074 if ( !isset( $profile['parameters'] ) ) {
1075 $profile['parameters'] = array();
1077 $profile['parameters']['profile'] = $id;
1079 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1080 $lang->commaList( $profile['namespace-messages'] ) : null;
1081 $out .= Xml::tags(
1082 'li',
1083 array(
1084 'class' => $this->profile === $id ? 'current' : 'normal'
1086 $this->makeSearchLink(
1087 $bareterm,
1088 array(),
1089 $this->msg( $profile['message'] )->text(),
1090 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1091 $profile['parameters']
1095 $out .= Xml::closeElement( 'ul' );
1096 $out .= Xml::closeElement( 'div' );
1098 // Results-info
1099 if ( $resultsShown > 0 ) {
1100 if ( $totalNum > 0 ) {
1101 $top = $this->msg( 'showingresultsheader' )
1102 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1103 ->params( wfEscapeWikiText( $term ) )
1104 ->numParams( $resultsShown )
1105 ->parse();
1106 } elseif ( $resultsShown >= $this->limit ) {
1107 $top = $this->msg( 'showingresults' )
1108 ->numParams( $this->limit, $this->offset + 1 )
1109 ->parse();
1110 } else {
1111 $top = $this->msg( 'showingresultsnum' )
1112 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1113 ->parse();
1115 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1116 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1120 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1121 $out .= Xml::closeElement( 'div' );
1123 return $out;
1127 * @param string $term
1128 * @return string
1130 protected function shortDialog( $term ) {
1131 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1132 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1133 // Term box
1134 $out .= Html::input( 'search', $term, 'search', array(
1135 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1136 'size' => '50',
1137 'autofocus',
1138 'class' => 'mw-ui-input',
1139 ) ) . "\n";
1140 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1141 $out .= Xml::submitButton(
1142 $this->msg( 'searchbutton' )->text(),
1143 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1144 ) . "\n";
1146 return $out . $this->didYouMeanHtml;
1150 * Make a search link with some target namespaces
1152 * @param string $term
1153 * @param array $namespaces Ignored
1154 * @param string $label Link's text
1155 * @param string $tooltip Link's tooltip
1156 * @param array $params Query string parameters
1157 * @return string HTML fragment
1159 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1160 $opt = $params;
1161 foreach ( $namespaces as $n ) {
1162 $opt['ns' . $n] = 1;
1165 $stParams = array_merge(
1166 array(
1167 'search' => $term,
1168 'fulltext' => $this->msg( 'search' )->text()
1170 $opt
1173 return Xml::element(
1174 'a',
1175 array(
1176 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1177 'title' => $tooltip
1179 $label
1184 * Check if query starts with image: prefix
1186 * @param string $term The string to check
1187 * @return bool
1189 protected function startsWithImage( $term ) {
1190 global $wgContLang;
1192 $parts = explode( ':', $term );
1193 if ( count( $parts ) > 1 ) {
1194 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1197 return false;
1201 * Check if query starts with all: prefix
1203 * @param string $term The string to check
1204 * @return bool
1206 protected function startsWithAll( $term ) {
1208 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1210 $parts = explode( ':', $term );
1211 if ( count( $parts ) > 1 ) {
1212 return $parts[0] == $allkeyword;
1215 return false;
1219 * @since 1.18
1221 * @return SearchEngine
1223 public function getSearchEngine() {
1224 if ( $this->searchEngine === null ) {
1225 $this->searchEngine = $this->searchEngineType ?
1226 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1229 return $this->searchEngine;
1233 * Current search profile.
1234 * @return null|string
1236 function getProfile() {
1237 return $this->profile;
1241 * Current namespaces.
1242 * @return array
1244 function getNamespaces() {
1245 return $this->namespaces;
1249 * Users of hook SpecialSearchSetupEngine can use this to
1250 * add more params to links to not lose selection when
1251 * user navigates search results.
1252 * @since 1.18
1254 * @param string $key
1255 * @param mixed $value
1257 public function setExtraParam( $key, $value ) {
1258 $this->extraParams[$key] = $value;
1261 protected function getGroupName() {
1262 return 'pages';