Merge "Improved rate limit log to mention IP"
[mediawiki.git] / includes / specials / SpecialSearch.php
blob2713a5f99844f38f0921098c19cfe99060142e5e
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, help, discussions...)
34 * For users tt replaces the set of enabled namespaces from the query
35 * string when applicable. Extensions can add new profiles with hooks
36 * with custom search options just for that profile.
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 $search->setLimitOffset( $this->limit, $this->offset );
211 $search->setNamespaces( $this->namespaces );
212 $search->prefix = $this->mPrefix;
213 $term = $search->transformSearchTerm( $term );
215 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
217 $this->setupPage( $term );
219 $out = $this->getOutput();
221 if ( $wgDisableTextSearch ) {
222 if ( $wgSearchForwardUrl ) {
223 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
224 $out->redirect( $url );
225 } else {
226 $out->addHTML(
227 Xml::openElement( 'fieldset' ) .
228 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
229 Xml::element(
230 'p',
231 array( 'class' => 'mw-searchdisabled' ),
232 $this->msg( 'searchdisabled' )->text()
234 $this->msg( 'googlesearch' )->rawParams(
235 htmlspecialchars( $term ),
236 'UTF-8',
237 $this->msg( 'searchbutton' )->escaped()
238 )->text() .
239 Xml::closeElement( 'fieldset' )
243 return;
246 $title = Title::newFromText( $term );
247 $showSuggestion = $title === null || !$title->isKnown();
248 $search->setShowSuggestion( $showSuggestion );
250 // fetch search results
251 $rewritten = $search->replacePrefixes( $term );
253 $titleMatches = $search->searchTitle( $rewritten );
254 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
255 $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
311 $out->addHtml(
312 # This is an awful awful ID name. It's not a table, but we
313 # named it poorly from when this was a table so now we're
314 # stuck with it
315 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
316 $this->shortDialog( $term ) .
317 Xml::closeElement( 'div' )
320 // Sometimes the search engine knows there are too many hits
321 if ( $titleMatches instanceof SearchResultTooMany ) {
322 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
324 return;
327 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
328 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
329 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
330 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
331 $out->addHTML( '</form>' );
333 // Empty query -- straight view of search form
334 return;
337 // Get number of results
338 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
339 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
340 // Total initial query matches (possible false positives)
341 $num = $titleMatchesNum + $textMatchesNum;
343 // Get total actual results (after second filtering, if any)
344 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
345 $titleMatches->getTotalHits() : $titleMatchesNum;
346 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
347 $textMatches->getTotalHits() : $textMatchesNum;
349 // get total number of results if backend can calculate it
350 $totalRes = 0;
351 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
352 $totalRes += $titleMatches->getTotalHits();
354 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
355 $totalRes += $textMatches->getTotalHits();
358 // show number of results and current offset
359 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
360 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
362 $out->addHtml( Xml::closeElement( 'form' ) );
363 $out->addHtml( "<div class='searchresults'>" );
365 // prev/next links
366 $prevnext = null;
367 if ( $num || $this->offset ) {
368 // Show the create link ahead
369 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
370 if ( $totalRes > $this->limit || $this->offset ) {
371 $prevnext = $this->getLanguage()->viewPrevNext(
372 $this->getPageTitle(),
373 $this->offset,
374 $this->limit,
375 $this->powerSearchOptions() + array( 'search' => $term ),
376 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
379 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
380 } else {
381 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
384 $out->parserOptions()->setEditSection( false );
385 if ( $titleMatches ) {
386 if ( $numTitleMatches > 0 ) {
387 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
388 $out->addHTML( $this->showMatches( $titleMatches ) );
390 $titleMatches->free();
392 if ( $textMatches && !$textStatus ) {
393 // output appropriate heading
394 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
395 // if no title matches the heading is redundant
396 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
399 // show interwiki results if any
400 if ( $textMatches->hasInterwikiResults() ) {
401 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
403 // show results
404 if ( $numTextMatches > 0 ) {
405 $out->addHTML( $this->showMatches( $textMatches ) );
408 $textMatches->free();
410 if ( $num === 0 ) {
411 if ( $textStatus ) {
412 $out->addHTML( '<div class="error">' .
413 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
414 } else {
415 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
416 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
417 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
420 $out->addHtml( "</div>" );
422 if ( $prevnext ) {
423 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
428 * @param Title $title
429 * @param int $num The number of search results found
430 * @param null|SearchResultSet $titleMatches Results from title search
431 * @param null|SearchResultSet $textMatches Results from text search
433 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
434 // show direct page/create link if applicable
436 // Check DBkey !== '' in case of fragment link only.
437 if ( is_null( $title ) || $title->getDBkey() === ''
438 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
439 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
441 // invalid title
442 // preserve the paragraph for margins etc...
443 $this->getOutput()->addHtml( '<p></p>' );
445 return;
448 if ( $title->isKnown() ) {
449 $messageName = 'searchmenu-exists';
450 } elseif ( $title->userCan( 'create', $this->getUser() ) ) {
451 $messageName = 'searchmenu-new';
452 } else {
453 $messageName = 'searchmenu-new-nocreate';
455 $params = array(
456 $messageName,
457 wfEscapeWikiText( $title->getPrefixedText() ),
458 Message::numParam( $num )
460 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
462 // Extensions using the hook might still return an empty $messageName
463 if ( $messageName ) {
464 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
465 } else {
466 // preserve the paragraph for margins etc...
467 $this->getOutput()->addHtml( '<p></p>' );
472 * @param string $term
474 protected function setupPage( $term ) {
475 # Should advanced UI be used?
476 $this->searchAdvanced = ( $this->profile === 'advanced' );
477 $out = $this->getOutput();
478 if ( strval( $term ) !== '' ) {
479 $out->setPageTitle( $this->msg( 'searchresults' ) );
480 $out->setHTMLTitle( $this->msg( 'pagetitle' )
481 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
482 ->inContentLanguage()->text()
485 // add javascript specific to special:search
486 $out->addModules( 'mediawiki.special.search' );
490 * Extract "power search" namespace settings from the request object,
491 * returning a list of index numbers to search.
493 * @param WebRequest $request
494 * @return array
496 protected function powerSearch( &$request ) {
497 $arr = array();
498 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
499 if ( $request->getCheck( 'ns' . $ns ) ) {
500 $arr[] = $ns;
504 return $arr;
508 * Reconstruct the 'power search' options for links
510 * @return array
512 protected function powerSearchOptions() {
513 $opt = array();
514 if ( $this->profile !== 'advanced' ) {
515 $opt['profile'] = $this->profile;
516 } else {
517 foreach ( $this->namespaces as $n ) {
518 $opt['ns' . $n] = 1;
522 return $opt + $this->extraParams;
526 * Show whole set of results
528 * @param SearchResultSet $matches
530 * @return string
532 protected function showMatches( &$matches ) {
533 global $wgContLang;
535 $profile = new ProfileSection( __METHOD__ );
536 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
538 $out = "<ul class='mw-search-results'>\n";
539 $result = $matches->next();
540 while ( $result ) {
541 $out .= $this->showHit( $result, $terms );
542 $result = $matches->next();
544 $out .= "</ul>\n";
546 // convert the whole thing to desired language variant
547 $out = $wgContLang->convert( $out );
549 return $out;
553 * Format a single hit result
555 * @param SearchResult $result
556 * @param array $terms Terms to highlight
558 * @return string
560 protected function showHit( $result, $terms ) {
561 $profile = new ProfileSection( __METHOD__ );
563 if ( $result->isBrokenTitle() ) {
564 return '';
567 $title = $result->getTitle();
569 $titleSnippet = $result->getTitleSnippet( $terms );
571 if ( $titleSnippet == '' ) {
572 $titleSnippet = null;
575 $link_t = clone $title;
577 wfRunHooks( 'ShowSearchHitTitle',
578 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
580 $link = Linker::linkKnown(
581 $link_t,
582 $titleSnippet
585 //If page content is not readable, just return the title.
586 //This is not quite safe, but better than showing excerpts from non-readable pages
587 //Note that hiding the entry entirely would screw up paging.
588 if ( !$title->userCan( 'read', $this->getUser() ) ) {
589 return "<li>{$link}</li>\n";
592 // If the page doesn't *exist*... our search index is out of date.
593 // The least confusing at this point is to drop the result.
594 // You may get less results, but... oh well. :P
595 if ( $result->isMissingRevision() ) {
596 return '';
599 // format redirects / relevant sections
600 $redirectTitle = $result->getRedirectTitle();
601 $redirectText = $result->getRedirectSnippet( $terms );
602 $sectionTitle = $result->getSectionTitle();
603 $sectionText = $result->getSectionSnippet( $terms );
604 $redirect = '';
606 if ( !is_null( $redirectTitle ) ) {
607 if ( $redirectText == '' ) {
608 $redirectText = null;
611 $redirect = "<span class='searchalttitle'>" .
612 $this->msg( 'search-redirect' )->rawParams(
613 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
614 "</span>";
617 $section = '';
619 if ( !is_null( $sectionTitle ) ) {
620 if ( $sectionText == '' ) {
621 $sectionText = null;
624 $section = "<span class='searchalttitle'>" .
625 $this->msg( 'search-section' )->rawParams(
626 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
627 "</span>";
630 // format text extract
631 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
633 $lang = $this->getLanguage();
635 // format score
636 if ( is_null( $result->getScore() ) ) {
637 // Search engine doesn't report scoring info
638 $score = '';
639 } else {
640 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
641 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
642 . ' - ';
645 // format description
646 $byteSize = $result->getByteSize();
647 $wordCount = $result->getWordCount();
648 $timestamp = $result->getTimestamp();
649 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
650 ->numParams( $wordCount )->escaped();
652 if ( $title->getNamespace() == NS_CATEGORY ) {
653 $cat = Category::newFromTitle( $title );
654 $size = $this->msg( 'search-result-category-size' )
655 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
656 ->escaped();
659 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
661 // link to related articles if supported
662 $related = '';
663 if ( $result->hasRelated() ) {
664 $stParams = array_merge(
665 $this->powerSearchOptions(),
666 array(
667 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
668 ':' . $title->getPrefixedText(),
669 'fulltext' => $this->msg( 'search' )->text()
673 $related = ' -- ' . Linker::linkKnown(
674 $this->getPageTitle(),
675 $this->msg( 'search-relatedarticle' )->text(),
676 array(),
677 $stParams
681 $fileMatch = '';
682 // Include a thumbnail for media files...
683 if ( $title->getNamespace() == NS_FILE ) {
684 $img = $result->getFile();
685 $img = $img ?: wfFindFile( $title );
686 if ( $result->isFileMatch() ) {
687 $fileMatch = "<span class='searchalttitle'>" .
688 $this->msg( 'search-file-match' )->escaped() . "</span>";
690 if ( $img ) {
691 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
692 if ( $thumb ) {
693 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
694 // Float doesn't seem to interact well with the bullets.
695 // Table messes up vertical alignment of the bullets.
696 // Bullets are therefore disabled (didn't look great anyway).
697 return "<li>" .
698 '<table class="searchResultImage">' .
699 '<tr>' .
700 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
701 $thumb->toHtml( array( 'desc-link' => true ) ) .
702 '</td>' .
703 '<td style="vertical-align: top;">' .
704 "{$link} {$fileMatch}" .
705 $extract .
706 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
707 '</td>' .
708 '</tr>' .
709 '</table>' .
710 "</li>\n";
715 $html = null;
717 if ( wfRunHooks( 'ShowSearchHit', array(
718 $this, $result, $terms,
719 &$link, &$redirect, &$section, &$extract,
720 &$score, &$size, &$date, &$related,
721 &$html
722 ) ) ) {
723 $html = "<li><div class='mw-search-result-heading'>" .
724 "{$link} {$redirect} {$section} {$fileMatch}</div> {$extract}\n" .
725 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
726 "</li>\n";
729 return $html;
733 * Show results from other wikis
735 * @param SearchResultSet|array $matches
736 * @param string $query
738 * @return string
740 protected function showInterwiki( $matches, $query ) {
741 global $wgContLang;
742 $profile = new ProfileSection( __METHOD__ );
744 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
745 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
746 $out .= "<ul class='mw-search-iwresults'>\n";
748 // work out custom project captions
749 $customCaptions = array();
750 // format per line <iwprefix>:<caption>
751 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
752 foreach ( $customLines as $line ) {
753 $parts = explode( ":", $line, 2 );
754 if ( count( $parts ) == 2 ) { // validate line
755 $customCaptions[$parts[0]] = $parts[1];
759 if ( !is_array( $matches ) ) {
760 $matches = array( $matches );
763 foreach ( $matches as $set ) {
764 $prev = null;
765 $result = $set->next();
766 while ( $result ) {
767 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
768 $prev = $result->getInterwikiPrefix();
769 $result = $set->next();
773 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
774 $out .= "</ul></div>\n";
776 // convert the whole thing to desired language variant
777 $out = $wgContLang->convert( $out );
779 return $out;
783 * Show single interwiki link
785 * @param SearchResult $result
786 * @param string $lastInterwiki
787 * @param string $query
788 * @param array $customCaptions iw prefix -> caption
790 * @return string
792 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
793 $profile = new ProfileSection( __METHOD__ );
795 if ( $result->isBrokenTitle() ) {
796 return '';
799 $title = $result->getTitle();
801 $titleSnippet = $result->getTitleSnippet();
803 if ( $titleSnippet == '' ) {
804 $titleSnippet = null;
807 $link = Linker::linkKnown(
808 $title,
809 $titleSnippet
812 // format redirect if any
813 $redirectTitle = $result->getRedirectTitle();
814 $redirectText = $result->getRedirectSnippet();
815 $redirect = '';
816 if ( !is_null( $redirectTitle ) ) {
817 if ( $redirectText == '' ) {
818 $redirectText = null;
821 $redirect = "<span class='searchalttitle'>" .
822 $this->msg( 'search-redirect' )->rawParams(
823 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
824 "</span>";
827 $out = "";
828 // display project name
829 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
830 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
831 // captions from 'search-interwiki-custom'
832 $caption = $customCaptions[$title->getInterwiki()];
833 } else {
834 // default is to show the hostname of the other wiki which might suck
835 // if there are many wikis on one hostname
836 $parsed = wfParseUrl( $title->getFullURL() );
837 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
839 // "more results" link (special page stuff could be localized, but we might not know target lang)
840 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
841 $searchLink = Linker::linkKnown(
842 $searchTitle,
843 $this->msg( 'search-interwiki-more' )->text(),
844 array(),
845 array(
846 'search' => $query,
847 'fulltext' => 'Search'
850 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
851 {$searchLink}</span>{$caption}</div>\n<ul>";
854 $out .= "<li>{$link} {$redirect}</li>\n";
856 return $out;
860 * @param string $profile
861 * @param string $term
862 * @return string
864 protected function getProfileForm( $profile, $term ) {
865 // Hidden stuff
866 $opts = array();
867 $opts['profile'] = $this->profile;
869 if ( $profile === 'advanced' ) {
870 return $this->powerSearchBox( $term, $opts );
871 } else {
872 $form = '';
873 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
875 return $form;
880 * Generates the power search box at [[Special:Search]]
882 * @param string $term Search term
883 * @param array $opts
884 * @return string HTML form
886 protected function powerSearchBox( $term, $opts ) {
887 global $wgContLang;
889 // Groups namespaces into rows according to subject
890 $rows = array();
891 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
892 $subject = MWNamespace::getSubject( $namespace );
893 if ( !array_key_exists( $subject, $rows ) ) {
894 $rows[$subject] = "";
897 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
898 if ( $name == '' ) {
899 $name = $this->msg( 'blanknamespace' )->text();
902 $rows[$subject] .=
903 Xml::openElement(
904 'td', array( 'style' => 'white-space: nowrap' )
906 Xml::checkLabel(
907 $name,
908 "ns{$namespace}",
909 "mw-search-ns{$namespace}",
910 in_array( $namespace, $this->namespaces )
912 Xml::closeElement( 'td' );
915 $rows = array_values( $rows );
916 $numRows = count( $rows );
918 // Lays out namespaces in multiple floating two-column tables so they'll
919 // be arranged nicely while still accommodating different screen widths
920 $namespaceTables = '';
921 for ( $i = 0; $i < $numRows; $i += 4 ) {
922 $namespaceTables .= Xml::openElement(
923 'table',
924 array( 'cellpadding' => 0, 'cellspacing' => 0 )
927 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
928 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
931 $namespaceTables .= Xml::closeElement( 'table' );
934 $showSections = array( 'namespaceTables' => $namespaceTables );
936 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
938 $hidden = '';
939 foreach ( $opts as $key => $value ) {
940 $hidden .= Html::hidden( $key, $value );
943 // Return final output
944 return Xml::openElement(
945 'fieldset',
946 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
948 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
949 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
950 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
951 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
952 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
953 $hidden .
954 Xml::closeElement( 'fieldset' );
958 * @return array
960 protected function getSearchProfiles() {
961 // Builds list of Search Types (profiles)
962 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
964 $profiles = array(
965 'default' => array(
966 'message' => 'searchprofile-articles',
967 'tooltip' => 'searchprofile-articles-tooltip',
968 'namespaces' => SearchEngine::defaultNamespaces(),
969 'namespace-messages' => SearchEngine::namespacesAsText(
970 SearchEngine::defaultNamespaces()
973 'images' => array(
974 'message' => 'searchprofile-images',
975 'tooltip' => 'searchprofile-images-tooltip',
976 'namespaces' => array( NS_FILE ),
978 'help' => array(
979 'message' => 'searchprofile-project',
980 'tooltip' => 'searchprofile-project-tooltip',
981 'namespaces' => SearchEngine::helpNamespaces(),
982 'namespace-messages' => SearchEngine::namespacesAsText(
983 SearchEngine::helpNamespaces()
986 'all' => array(
987 'message' => 'searchprofile-everything',
988 'tooltip' => 'searchprofile-everything-tooltip',
989 'namespaces' => $nsAllSet,
991 'advanced' => array(
992 'message' => 'searchprofile-advanced',
993 'tooltip' => 'searchprofile-advanced-tooltip',
994 'namespaces' => self::NAMESPACES_CURRENT,
998 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1000 foreach ( $profiles as &$data ) {
1001 if ( !is_array( $data['namespaces'] ) ) {
1002 continue;
1004 sort( $data['namespaces'] );
1007 return $profiles;
1011 * @param string $term
1012 * @param int $resultsShown
1013 * @param int $totalNum
1014 * @return string
1016 protected function formHeader( $term, $resultsShown, $totalNum ) {
1017 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1019 $bareterm = $term;
1020 if ( $this->startsWithImage( $term ) ) {
1021 // Deletes prefixes
1022 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1025 $profiles = $this->getSearchProfiles();
1026 $lang = $this->getLanguage();
1028 // Outputs XML for Search Types
1029 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1030 $out .= Xml::openElement( 'ul' );
1031 foreach ( $profiles as $id => $profile ) {
1032 if ( !isset( $profile['parameters'] ) ) {
1033 $profile['parameters'] = array();
1035 $profile['parameters']['profile'] = $id;
1037 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1038 $lang->commaList( $profile['namespace-messages'] ) : null;
1039 $out .= Xml::tags(
1040 'li',
1041 array(
1042 'class' => $this->profile === $id ? 'current' : 'normal'
1044 $this->makeSearchLink(
1045 $bareterm,
1046 array(),
1047 $this->msg( $profile['message'] )->text(),
1048 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1049 $profile['parameters']
1053 $out .= Xml::closeElement( 'ul' );
1054 $out .= Xml::closeElement( 'div' );
1056 // Results-info
1057 if ( $resultsShown > 0 ) {
1058 if ( $totalNum > 0 ) {
1059 $top = $this->msg( 'showingresultsheader' )
1060 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1061 ->params( wfEscapeWikiText( $term ) )
1062 ->numParams( $resultsShown )
1063 ->parse();
1064 } elseif ( $resultsShown >= $this->limit ) {
1065 $top = $this->msg( 'showingresults' )
1066 ->numParams( $this->limit, $this->offset + 1 )
1067 ->parse();
1068 } else {
1069 $top = $this->msg( 'showingresultsnum' )
1070 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1071 ->parse();
1073 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1074 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1078 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1079 $out .= Xml::closeElement( 'div' );
1081 return $out;
1085 * @param string $term
1086 * @return string
1088 protected function shortDialog( $term ) {
1089 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1090 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1091 // Term box
1092 $out .= Html::input( 'search', $term, 'search', array(
1093 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1094 'size' => '50',
1095 'autofocus',
1096 'class' => 'mw-ui-input',
1097 ) ) . "\n";
1098 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1099 $out .= Xml::submitButton(
1100 $this->msg( 'searchbutton' )->text(),
1101 array( 'class' => array( 'mw-ui-button', 'mw-ui-progressive' ) )
1102 ) . "\n";
1104 return $out . $this->didYouMeanHtml;
1108 * Make a search link with some target namespaces
1110 * @param string $term
1111 * @param array $namespaces Ignored
1112 * @param string $label Link's text
1113 * @param string $tooltip Link's tooltip
1114 * @param array $params Query string parameters
1115 * @return string HTML fragment
1117 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1118 $opt = $params;
1119 foreach ( $namespaces as $n ) {
1120 $opt['ns' . $n] = 1;
1123 $stParams = array_merge(
1124 array(
1125 'search' => $term,
1126 'fulltext' => $this->msg( 'search' )->text()
1128 $opt
1131 return Xml::element(
1132 'a',
1133 array(
1134 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1135 'title' => $tooltip
1137 $label
1142 * Check if query starts with image: prefix
1144 * @param string $term The string to check
1145 * @return bool
1147 protected function startsWithImage( $term ) {
1148 global $wgContLang;
1150 $parts = explode( ':', $term );
1151 if ( count( $parts ) > 1 ) {
1152 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1155 return false;
1159 * Check if query starts with all: prefix
1161 * @param string $term The string to check
1162 * @return bool
1164 protected function startsWithAll( $term ) {
1166 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1168 $parts = explode( ':', $term );
1169 if ( count( $parts ) > 1 ) {
1170 return $parts[0] == $allkeyword;
1173 return false;
1177 * @since 1.18
1179 * @return SearchEngine
1181 public function getSearchEngine() {
1182 if ( $this->searchEngine === null ) {
1183 $this->searchEngine = $this->searchEngineType ?
1184 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1187 return $this->searchEngine;
1191 * Current search profile.
1192 * @return null|string
1194 function getProfile() {
1195 return $this->profile;
1199 * Current namespaces.
1200 * @return array
1202 function getNamespaces() {
1203 return $this->namespaces;
1207 * Users of hook SpecialSearchSetupEngine can use this to
1208 * add more params to links to not lose selection when
1209 * user navigates search results.
1210 * @since 1.18
1212 * @param string $key
1213 * @param mixed $value
1215 public function setExtraParam( $key, $value ) {
1216 $this->extraParams[$key] = $value;
1219 protected function getGroupName() {
1220 return 'pages';