Merge "Remove unused messages 'edit-externally' and 'edit-externally-help'"
[mediawiki.git] / includes / specials / SpecialSearch.php
blobbdcecf9477733be95c15d90557cc22a26da346c6
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 * null|string
39 protected $profile;
40 function getProfile() { return $this->profile; }
42 /// Search engine
43 protected $searchEngine;
45 /// Search engine type, if not default
46 protected $searchEngineType;
48 /// For links
49 protected $extraParams = array();
51 /// No idea, apparently used by some other classes
52 protected $mPrefix;
54 /**
55 * @var int
57 protected $limit, $offset;
59 /**
60 * @var array
62 protected $namespaces;
63 function getNamespaces() { return $this->namespaces; }
65 /**
66 * @var bool
68 protected $searchRedirects;
70 /**
71 * @var string
73 protected $didYouMeanHtml, $fulltext;
75 const NAMESPACES_CURRENT = 'sense';
77 public function __construct() {
78 parent::__construct( 'Search' );
81 /**
82 * Entry point
84 * @param string $par or null
86 public function execute( $par ) {
87 $this->setHeaders();
88 $this->outputHeader();
89 $out = $this->getOutput();
90 $out->allowClickjacking();
91 $out->addModuleStyles( array(
92 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui'
93 ) );
95 // Strip underscores from title parameter; most of the time we'll want
96 // text form here. But don't strip underscores from actual text params!
97 $titleParam = str_replace( '_', ' ', $par );
99 $request = $this->getRequest();
101 // Fetch the search term
102 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
104 $this->load();
106 $this->searchEngineType = $request->getVal( 'srbackend' );
108 if ( $request->getVal( 'fulltext' )
109 || !is_null( $request->getVal( 'offset' ) )
110 || !is_null( $request->getVal( 'searchx' ) )
112 $this->showResults( $search );
113 } else {
114 $this->goResult( $search );
119 * Set up basic search parameters from the request and user settings.
121 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
123 public function load() {
124 $request = $this->getRequest();
125 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, 'searchlimit' );
126 $this->mPrefix = $request->getVal( 'prefix', '' );
128 $user = $this->getUser();
130 # Extract manually requested namespaces
131 $nslist = $this->powerSearch( $request );
132 if ( !count( $nslist ) ) {
133 # Fallback to user preference
134 $nslist = SearchEngine::userNamespaces( $user );
137 $profile = null;
138 if ( !count( $nslist ) ) {
139 $profile = 'default';
142 $profile = $request->getVal( 'profile', $profile );
143 $profiles = $this->getSearchProfiles();
144 if ( $profile === null ) {
145 // BC with old request format
146 $profile = 'advanced';
147 foreach ( $profiles as $key => $data ) {
148 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
149 $profile = $key;
152 $this->namespaces = $nslist;
153 } elseif ( $profile === 'advanced' ) {
154 $this->namespaces = $nslist;
155 } else {
156 if ( isset( $profiles[$profile]['namespaces'] ) ) {
157 $this->namespaces = $profiles[$profile]['namespaces'];
158 } else {
159 // Unknown profile requested
160 $profile = 'default';
161 $this->namespaces = $profiles['default']['namespaces'];
165 // Redirects defaults to true, but we don't know whether it was ticked of or just missing
166 $default = $request->getBool( 'profile' ) ? 0 : 1;
167 $this->searchRedirects = $request->getBool( 'redirs', $default ) ? 1 : 0;
168 $this->didYouMeanHtml = ''; # html of did you mean... link
169 $this->fulltext = $request->getVal( 'fulltext' );
170 $this->profile = $profile;
174 * If an exact title match can be found, jump straight ahead to it.
176 * @param $term String
178 public function goResult( $term ) {
179 $this->setupPage( $term );
180 # Try to go to page as entered.
181 $t = Title::newFromText( $term );
182 # If the string cannot be used to create a title
183 if ( is_null( $t ) ) {
184 $this->showResults( $term );
185 return;
187 # If there's an exact or very near match, jump right there.
188 $t = SearchEngine::getNearMatch( $term );
190 if ( !wfRunHooks( 'SpecialSearchGo', array( &$t, &$term ) ) ) {
191 # Hook requested termination
192 return;
195 if ( !is_null( $t ) ) {
196 $this->getOutput()->redirect( $t->getFullURL() );
197 return;
199 # No match, generate an edit URL
200 $t = Title::newFromText( $term );
201 if ( !is_null( $t ) ) {
202 global $wgGoToEdit;
203 wfRunHooks( 'SpecialSearchNogomatch', array( &$t ) );
204 wfDebugLog( 'nogomatch', $t->getText(), false );
206 # If the feature is enabled, go straight to the edit page
207 if ( $wgGoToEdit ) {
208 $this->getOutput()->redirect( $t->getFullURL( array( 'action' => 'edit' ) ) );
209 return;
212 $this->showResults( $term );
216 * @param $term String
218 public function showResults( $term ) {
219 global $wgDisableTextSearch, $wgSearchForwardUrl, $wgContLang, $wgScript;
220 wfProfileIn( __METHOD__ );
222 $search = $this->getSearchEngine();
223 $search->setLimitOffset( $this->limit, $this->offset );
224 $search->setNamespaces( $this->namespaces );
225 $search->showRedirects = $this->searchRedirects; // BC
226 $search->setFeatureData( 'list-redirects', $this->searchRedirects );
227 $search->prefix = $this->mPrefix;
228 $term = $search->transformSearchTerm( $term );
230 wfRunHooks( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
232 $this->setupPage( $term );
234 $out = $this->getOutput();
236 if ( $wgDisableTextSearch ) {
237 if ( $wgSearchForwardUrl ) {
238 $url = str_replace( '$1', urlencode( $term ), $wgSearchForwardUrl );
239 $out->redirect( $url );
240 } else {
241 $out->addHTML(
242 Xml::openElement( 'fieldset' ) .
243 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
244 Xml::element( 'p', array( 'class' => 'mw-searchdisabled' ), $this->msg( 'searchdisabled' )->text() ) .
245 $this->msg( 'googlesearch' )->rawParams(
246 htmlspecialchars( $term ),
247 'UTF-8',
248 $this->msg( 'searchbutton' )->escaped()
249 )->text() .
250 Xml::closeElement( 'fieldset' )
253 wfProfileOut( __METHOD__ );
254 return;
257 $t = Title::newFromText( $term );
259 // fetch search results
260 $rewritten = $search->replacePrefixes( $term );
262 $titleMatches = $search->searchTitle( $rewritten );
263 if ( !( $titleMatches instanceof SearchResultTooMany ) ) {
264 $textMatches = $search->searchText( $rewritten );
267 $textStatus = null;
268 if ( $textMatches instanceof Status ) {
269 $textStatus = $textMatches;
270 $textMatches = null;
273 // did you mean... suggestions
274 if ( $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
275 $st = SpecialPage::getTitleFor( 'Search' );
277 # mirror Go/Search behavior of original request ..
278 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
280 if ( $this->fulltext != null ) {
281 $didYouMeanParams['fulltext'] = $this->fulltext;
284 $stParams = array_merge(
285 $didYouMeanParams,
286 $this->powerSearchOptions()
289 $suggestionSnippet = $textMatches->getSuggestionSnippet();
291 if ( $suggestionSnippet == '' ) {
292 $suggestionSnippet = null;
295 $suggestLink = Linker::linkKnown(
296 $st,
297 $suggestionSnippet,
298 array(),
299 $stParams
302 $this->didYouMeanHtml = '<div class="searchdidyoumean">' . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
305 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
306 # Hook requested termination
307 wfProfileOut( __METHOD__ );
308 return;
311 // start rendering the page
312 $out->addHtml(
313 Xml::openElement(
314 'form',
315 array(
316 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
317 'method' => 'get',
318 'action' => $wgScript
322 $out->addHtml(
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
325 # stuck with it
326 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
327 $this->shortDialog( $term ) .
328 Xml::closeElement( 'div' )
331 // Sometimes the search engine knows there are too many hits
332 if ( $titleMatches instanceof SearchResultTooMany ) {
333 $out->wrapWikiMsg( "==$1==\n", 'toomanymatches' );
334 wfProfileOut( __METHOD__ );
335 return;
338 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
339 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
340 $out->addHTML( $this->formHeader( $term, 0, 0 ) );
341 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
342 $out->addHTML( '</form>' );
343 // Empty query -- straight view of search form
344 wfProfileOut( __METHOD__ );
345 return;
348 // Get number of results
349 $titleMatchesNum = $titleMatches ? $titleMatches->numRows() : 0;
350 $textMatchesNum = $textMatches ? $textMatches->numRows() : 0;
351 // Total initial query matches (possible false positives)
352 $num = $titleMatchesNum + $textMatchesNum;
354 // Get total actual results (after second filtering, if any)
355 $numTitleMatches = $titleMatches && !is_null( $titleMatches->getTotalHits() ) ?
356 $titleMatches->getTotalHits() : $titleMatchesNum;
357 $numTextMatches = $textMatches && !is_null( $textMatches->getTotalHits() ) ?
358 $textMatches->getTotalHits() : $textMatchesNum;
360 // get total number of results if backend can calculate it
361 $totalRes = 0;
362 if ( $titleMatches && !is_null( $titleMatches->getTotalHits() ) ) {
363 $totalRes += $titleMatches->getTotalHits();
365 if ( $textMatches && !is_null( $textMatches->getTotalHits() ) ) {
366 $totalRes += $textMatches->getTotalHits();
369 // show number of results and current offset
370 $out->addHTML( $this->formHeader( $term, $num, $totalRes ) );
371 $out->addHtml( $this->getProfileForm( $this->profile, $term ) );
373 $out->addHtml( Xml::closeElement( 'form' ) );
374 $out->addHtml( "<div class='searchresults'>" );
376 // prev/next links
377 if ( $num || $this->offset ) {
378 // Show the create link ahead
379 $this->showCreateLink( $t );
380 $prevnext = $this->getLanguage()->viewPrevNext( $this->getTitle(), $this->offset, $this->limit,
381 $this->powerSearchOptions() + array( 'search' => $term ),
382 max( $titleMatchesNum, $textMatchesNum ) < $this->limit
384 //$out->addHTML( "<p class='mw-search-pager-top'>{$prevnext}</p>\n" );
385 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
386 } else {
387 wfRunHooks( 'SpecialSearchNoResults', array( $term ) );
390 $out->parserOptions()->setEditSection( false );
391 if ( $titleMatches ) {
392 if ( $numTitleMatches > 0 ) {
393 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
394 $out->addHTML( $this->showMatches( $titleMatches ) );
396 $titleMatches->free();
398 if ( $textMatches && !$textStatus ) {
399 // output appropriate heading
400 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
401 // if no title matches the heading is redundant
402 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
403 } elseif ( $totalRes == 0 ) {
404 # Don't show the 'no text matches' if we received title matches
405 # $out->wrapWikiMsg( "==$1==\n", 'notextmatches' );
407 // show interwiki results if any
408 if ( $textMatches->hasInterwikiResults() ) {
409 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
411 // show results
412 if ( $numTextMatches > 0 ) {
413 $out->addHTML( $this->showMatches( $textMatches ) );
416 $textMatches->free();
418 if ( $num === 0 ) {
419 if ( $textStatus ) {
420 $out->addHTML( '<div class="error">' .
421 htmlspecialchars( $textStatus->getWikiText( 'search-error' ) ) . '</div>' );
422 } else {
423 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
424 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
425 $this->showCreateLink( $t );
428 $out->addHtml( "</div>" );
430 if ( $num || $this->offset ) {
431 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
433 wfRunHooks( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
434 wfProfileOut( __METHOD__ );
438 * @param $t Title
440 protected function showCreateLink( $t ) {
441 // show direct page/create link if applicable
443 // Check DBkey !== '' in case of fragment link only.
444 if ( is_null( $t ) || $t->getDBkey() === '' ) {
445 // invalid title
446 // preserve the paragraph for margins etc...
447 $this->getOutput()->addHtml( '<p></p>' );
448 return;
451 if ( $t->isKnown() ) {
452 $messageName = 'searchmenu-exists';
453 } elseif ( $t->userCan( 'create', $this->getUser() ) ) {
454 $messageName = 'searchmenu-new';
455 } else {
456 $messageName = 'searchmenu-new-nocreate';
458 $params = array( $messageName, wfEscapeWikiText( $t->getPrefixedText() ) );
459 wfRunHooks( 'SpecialSearchCreateLink', array( $t, &$params ) );
461 // Extensions using the hook might still return an empty $messageName
462 if ( $messageName ) {
463 $this->getOutput()->wrapWikiMsg( "<p class=\"mw-search-createlink\">\n$1</p>", $params );
464 } else {
465 // preserve the paragraph for margins etc...
466 $this->getOutput()->addHtml( '<p></p>' );
471 * @param $term string
473 protected function setupPage( $term ) {
474 # Should advanced UI be used?
475 $this->searchAdvanced = ( $this->profile === 'advanced' );
476 $out = $this->getOutput();
477 if ( strval( $term ) !== '' ) {
478 $out->setPageTitle( $this->msg( 'searchresults' ) );
479 $out->setHTMLTitle( $this->msg( 'pagetitle' )
480 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term ) )
481 ->inContentLanguage()->text()
484 // add javascript specific to special:search
485 $out->addModules( 'mediawiki.special.search' );
489 * Extract "power search" namespace settings from the request object,
490 * returning a list of index numbers to search.
492 * @param $request WebRequest
493 * @return Array
495 protected function powerSearch( &$request ) {
496 $arr = array();
497 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
498 if ( $request->getCheck( 'ns' . $ns ) ) {
499 $arr[] = $ns;
503 return $arr;
507 * Reconstruct the 'power search' options for links
509 * @return Array
511 protected function powerSearchOptions() {
512 $opt = array();
513 $opt['redirs'] = $this->searchRedirects ? 1 : 0;
514 if ( $this->profile !== 'advanced' ) {
515 $opt['profile'] = $this->profile;
516 } else {
517 foreach ( $this->namespaces as $n ) {
518 $opt['ns' . $n] = 1;
521 return $opt + $this->extraParams;
525 * Show whole set of results
527 * @param $matches SearchResultSet
529 * @return string
531 protected function showMatches( &$matches ) {
532 global $wgContLang;
533 wfProfileIn( __METHOD__ );
535 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
537 $out = "";
538 $infoLine = $matches->getInfo();
539 if ( !is_null( $infoLine ) ) {
540 $out .= "\n<!-- {$infoLine} -->\n";
542 $out .= "<ul class='mw-search-results'>\n";
543 $result = $matches->next();
544 while ( $result ) {
545 $out .= $this->showHit( $result, $terms );
546 $result = $matches->next();
548 $out .= "</ul>\n";
550 // convert the whole thing to desired language variant
551 $out = $wgContLang->convert( $out );
552 wfProfileOut( __METHOD__ );
553 return $out;
557 * Format a single hit result
559 * @param $result SearchResult
560 * @param array $terms terms to highlight
562 * @return string
564 protected function showHit( $result, $terms ) {
565 wfProfileIn( __METHOD__ );
567 if ( $result->isBrokenTitle() ) {
568 wfProfileOut( __METHOD__ );
569 return "<!-- Broken link in search result -->\n";
572 $t = $result->getTitle();
574 $titleSnippet = $result->getTitleSnippet( $terms );
576 if ( $titleSnippet == '' ) {
577 $titleSnippet = null;
580 $link_t = clone $t;
582 wfRunHooks( 'ShowSearchHitTitle',
583 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
585 $link = Linker::linkKnown(
586 $link_t,
587 $titleSnippet
590 //If page content is not readable, just return the title.
591 //This is not quite safe, but better than showing excerpts from non-readable pages
592 //Note that hiding the entry entirely would screw up paging.
593 if ( !$t->userCan( 'read', $this->getUser() ) ) {
594 wfProfileOut( __METHOD__ );
595 return "<li>{$link}</li>\n";
598 // If the page doesn't *exist*... our search index is out of date.
599 // The least confusing at this point is to drop the result.
600 // You may get less results, but... oh well. :P
601 if ( $result->isMissingRevision() ) {
602 wfProfileOut( __METHOD__ );
603 return "<!-- missing page " . htmlspecialchars( $t->getPrefixedText() ) . "-->\n";
606 // format redirects / relevant sections
607 $redirectTitle = $result->getRedirectTitle();
608 $redirectText = $result->getRedirectSnippet( $terms );
609 $sectionTitle = $result->getSectionTitle();
610 $sectionText = $result->getSectionSnippet( $terms );
611 $redirect = '';
613 if ( !is_null( $redirectTitle ) ) {
614 if ( $redirectText == '' ) {
615 $redirectText = null;
618 $redirect = "<span class='searchalttitle'>" .
619 $this->msg( 'search-redirect' )->rawParams(
620 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
621 "</span>";
624 $section = '';
626 if ( !is_null( $sectionTitle ) ) {
627 if ( $sectionText == '' ) {
628 $sectionText = null;
631 $section = "<span class='searchalttitle'>" .
632 $this->msg( 'search-section' )->rawParams(
633 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
634 "</span>";
637 // format text extract
638 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
640 $lang = $this->getLanguage();
642 // format score
643 if ( is_null( $result->getScore() ) ) {
644 // Search engine doesn't report scoring info
645 $score = '';
646 } else {
647 $percent = sprintf( '%2.1f', $result->getScore() * 100 );
648 $score = $this->msg( 'search-result-score' )->numParams( $percent )->text()
649 . ' - ';
652 // format description
653 $byteSize = $result->getByteSize();
654 $wordCount = $result->getWordCount();
655 $timestamp = $result->getTimestamp();
656 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
657 ->numParams( $wordCount )->escaped();
659 if ( $t->getNamespace() == NS_CATEGORY ) {
660 $cat = Category::newFromTitle( $t );
661 $size = $this->msg( 'search-result-category-size' )
662 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
663 ->escaped();
666 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
668 // link to related articles if supported
669 $related = '';
670 if ( $result->hasRelated() ) {
671 $st = SpecialPage::getTitleFor( 'Search' );
672 $stParams = array_merge(
673 $this->powerSearchOptions(),
674 array(
675 'search' => $this->msg( 'searchrelated' )->inContentLanguage()->text() .
676 ':' . $t->getPrefixedText(),
677 'fulltext' => $this->msg( 'search' )->text()
681 $related = ' -- ' . Linker::linkKnown(
682 $st,
683 $this->msg( 'search-relatedarticle' )->text(),
684 array(),
685 $stParams
689 // Include a thumbnail for media files...
690 if ( $t->getNamespace() == NS_FILE ) {
691 $img = wfFindFile( $t );
692 if ( $img ) {
693 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
694 if ( $thumb ) {
695 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
696 wfProfileOut( __METHOD__ );
697 // Float doesn't seem to interact well with the bullets.
698 // Table messes up vertical alignment of the bullets.
699 // Bullets are therefore disabled (didn't look great anyway).
700 return "<li>" .
701 '<table class="searchResultImage">' .
702 '<tr>' .
703 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
704 $thumb->toHtml( array( 'desc-link' => true ) ) .
705 '</td>' .
706 '<td style="vertical-align: top;">' .
707 $link .
708 $extract .
709 "<div class='mw-search-result-data'>{$score}{$desc} - {$date}{$related}</div>" .
710 '</td>' .
711 '</tr>' .
712 '</table>' .
713 "</li>\n";
718 $html = null;
720 if ( wfRunHooks( 'ShowSearchHit', array(
721 $this, $result, $terms,
722 &$link, &$redirect, &$section, &$extract,
723 &$score, &$size, &$date, &$related,
724 &$html
725 ) ) ) {
726 $html = "<li><div class='mw-search-result-heading'>{$link} {$redirect} {$section}</div> {$extract}\n" .
727 "<div class='mw-search-result-data'>{$score}{$size} - {$date}{$related}</div>" .
728 "</li>\n";
731 wfProfileOut( __METHOD__ );
732 return $html;
736 * Show results from other wikis
738 * @param $matches SearchResultSet
739 * @param $query String
741 * @return string
743 protected function showInterwiki( $matches, $query ) {
744 global $wgContLang;
745 wfProfileIn( __METHOD__ );
746 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
748 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
749 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
750 $out .= "<ul class='mw-search-iwresults'>\n";
752 // work out custom project captions
753 $customCaptions = array();
754 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() ); // format per line <iwprefix>:<caption>
755 foreach ( $customLines as $line ) {
756 $parts = explode( ":", $line, 2 );
757 if ( count( $parts ) == 2 ) { // validate line
758 $customCaptions[$parts[0]] = $parts[1];
762 $prev = null;
763 $result = $matches->next();
764 while ( $result ) {
765 $out .= $this->showInterwikiHit( $result, $prev, $terms, $query, $customCaptions );
766 $prev = $result->getInterwikiPrefix();
767 $result = $matches->next();
769 // TODO: should support paging in a non-confusing way (not sure how though, maybe via ajax)..
770 $out .= "</ul></div>\n";
772 // convert the whole thing to desired language variant
773 $out = $wgContLang->convert( $out );
774 wfProfileOut( __METHOD__ );
775 return $out;
779 * Show single interwiki link
781 * @param $result SearchResult
782 * @param $lastInterwiki String
783 * @param $terms Array
784 * @param $query String
785 * @param array $customCaptions iw prefix -> caption
787 * @return string
789 protected function showInterwikiHit( $result, $lastInterwiki, $terms, $query, $customCaptions ) {
790 wfProfileIn( __METHOD__ );
792 if ( $result->isBrokenTitle() ) {
793 wfProfileOut( __METHOD__ );
794 return "<!-- Broken link in search result -->\n";
797 $t = $result->getTitle();
799 $titleSnippet = $result->getTitleSnippet( $terms );
801 if ( $titleSnippet == '' ) {
802 $titleSnippet = null;
805 $link = Linker::linkKnown(
807 $titleSnippet
810 // format redirect if any
811 $redirectTitle = $result->getRedirectTitle();
812 $redirectText = $result->getRedirectSnippet( $terms );
813 $redirect = '';
814 if ( !is_null( $redirectTitle ) ) {
815 if ( $redirectText == '' ) {
816 $redirectText = null;
819 $redirect = "<span class='searchalttitle'>" .
820 $this->msg( 'search-redirect' )->rawParams(
821 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
822 "</span>";
825 $out = "";
826 // display project name
827 if ( is_null( $lastInterwiki ) || $lastInterwiki != $t->getInterwiki() ) {
828 if ( array_key_exists( $t->getInterwiki(), $customCaptions ) ) {
829 // captions from 'search-interwiki-custom'
830 $caption = $customCaptions[$t->getInterwiki()];
831 } else {
832 // default is to show the hostname of the other wiki which might suck
833 // if there are many wikis on one hostname
834 $parsed = wfParseUrl( $t->getFullURL() );
835 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
837 // "more results" link (special page stuff could be localized, but we might not know target lang)
838 $searchTitle = Title::newFromText( $t->getInterwiki() . ":Special:Search" );
839 $searchLink = Linker::linkKnown(
840 $searchTitle,
841 $this->msg( 'search-interwiki-more' )->text(),
842 array(),
843 array(
844 'search' => $query,
845 'fulltext' => 'Search'
848 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
849 {$searchLink}</span>{$caption}</div>\n<ul>";
852 $out .= "<li>{$link} {$redirect}</li>\n";
853 wfProfileOut( __METHOD__ );
854 return $out;
858 * @param $profile
859 * @param $term
860 * @return String
862 protected function getProfileForm( $profile, $term ) {
863 // Hidden stuff
864 $opts = array();
865 $opts['redirs'] = $this->searchRedirects;
866 $opts['profile'] = $this->profile;
868 if ( $profile === 'advanced' ) {
869 return $this->powerSearchBox( $term, $opts );
870 } else {
871 $form = '';
872 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $profile, $term, $opts ) );
873 return $form;
878 * Generates the power search box at [[Special:Search]]
880 * @param string $term search term
881 * @param $opts array
882 * @return String: HTML form
884 protected function powerSearchBox( $term, $opts ) {
885 global $wgContLang;
887 // Groups namespaces into rows according to subject
888 $rows = array();
889 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
890 $subject = MWNamespace::getSubject( $namespace );
891 if ( !array_key_exists( $subject, $rows ) ) {
892 $rows[$subject] = "";
895 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
896 if ( $name == '' ) {
897 $name = $this->msg( 'blanknamespace' )->text();
900 $rows[$subject] .=
901 Xml::openElement(
902 'td', array( 'style' => 'white-space: nowrap' )
904 Xml::checkLabel(
905 $name,
906 "ns{$namespace}",
907 "mw-search-ns{$namespace}",
908 in_array( $namespace, $this->namespaces )
910 Xml::closeElement( 'td' );
913 $rows = array_values( $rows );
914 $numRows = count( $rows );
916 // Lays out namespaces in multiple floating two-column tables so they'll
917 // be arranged nicely while still accommodating different screen widths
918 $namespaceTables = '';
919 for ( $i = 0; $i < $numRows; $i += 4 ) {
920 $namespaceTables .= Xml::openElement(
921 'table',
922 array( 'cellpadding' => 0, 'cellspacing' => 0 )
925 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
926 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
929 $namespaceTables .= Xml::closeElement( 'table' );
932 $showSections = array( 'namespaceTables' => $namespaceTables );
934 // Show redirects check only if backend supports it
935 if ( $this->getSearchEngine()->supports( 'list-redirects' ) ) {
936 $showSections['redirects'] =
937 Xml::checkLabel( $this->msg( 'powersearch-redir' )->text(), 'redirs', 'redirs', $this->searchRedirects );
940 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
942 $hidden = '';
943 unset( $opts['redirs'] );
944 foreach ( $opts as $key => $value ) {
945 $hidden .= Html::hidden( $key, $value );
947 // Return final output
948 return Xml::openElement(
949 'fieldset',
950 array( 'id' => 'mw-searchoptions', 'style' => 'margin:0em;' )
952 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
953 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
954 Html::element( 'div', array( 'id' => 'mw-search-togglebox' ) ) .
955 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
956 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
957 $hidden .
958 Xml::closeElement( 'fieldset' );
962 * @return array
964 protected function getSearchProfiles() {
965 // Builds list of Search Types (profiles)
966 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
968 $profiles = array(
969 'default' => array(
970 'message' => 'searchprofile-articles',
971 'tooltip' => 'searchprofile-articles-tooltip',
972 'namespaces' => SearchEngine::defaultNamespaces(),
973 'namespace-messages' => SearchEngine::namespacesAsText(
974 SearchEngine::defaultNamespaces()
977 'images' => array(
978 'message' => 'searchprofile-images',
979 'tooltip' => 'searchprofile-images-tooltip',
980 'namespaces' => array( NS_FILE ),
982 'help' => array(
983 'message' => 'searchprofile-project',
984 'tooltip' => 'searchprofile-project-tooltip',
985 'namespaces' => SearchEngine::helpNamespaces(),
986 'namespace-messages' => SearchEngine::namespacesAsText(
987 SearchEngine::helpNamespaces()
990 'all' => array(
991 'message' => 'searchprofile-everything',
992 'tooltip' => 'searchprofile-everything-tooltip',
993 'namespaces' => $nsAllSet,
995 'advanced' => array(
996 'message' => 'searchprofile-advanced',
997 'tooltip' => 'searchprofile-advanced-tooltip',
998 'namespaces' => self::NAMESPACES_CURRENT,
1002 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
1004 foreach ( $profiles as &$data ) {
1005 if ( !is_array( $data['namespaces'] ) ) {
1006 continue;
1008 sort( $data['namespaces'] );
1011 return $profiles;
1015 * @param $term
1016 * @param $resultsShown
1017 * @param $totalNum
1018 * @return string
1020 protected function formHeader( $term, $resultsShown, $totalNum ) {
1021 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
1023 $bareterm = $term;
1024 if ( $this->startsWithImage( $term ) ) {
1025 // Deletes prefixes
1026 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1029 $profiles = $this->getSearchProfiles();
1030 $lang = $this->getLanguage();
1032 // Outputs XML for Search Types
1033 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1034 $out .= Xml::openElement( 'ul' );
1035 foreach ( $profiles as $id => $profile ) {
1036 if ( !isset( $profile['parameters'] ) ) {
1037 $profile['parameters'] = array();
1039 $profile['parameters']['profile'] = $id;
1041 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1042 $lang->commaList( $profile['namespace-messages'] ) : null;
1043 $out .= Xml::tags(
1044 'li',
1045 array(
1046 'class' => $this->profile === $id ? 'current' : 'normal'
1048 $this->makeSearchLink(
1049 $bareterm,
1050 array(),
1051 $this->msg( $profile['message'] )->text(),
1052 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1053 $profile['parameters']
1057 $out .= Xml::closeElement( 'ul' );
1058 $out .= Xml::closeElement( 'div' );
1060 // Results-info
1061 if ( $resultsShown > 0 ) {
1062 if ( $totalNum > 0 ) {
1063 $top = $this->msg( 'showingresultsheader' )
1064 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1065 ->params( wfEscapeWikiText( $term ) )
1066 ->numParams( $resultsShown )
1067 ->parse();
1068 } elseif ( $resultsShown >= $this->limit ) {
1069 $top = $this->msg( 'showingresults' )
1070 ->numParams( $this->limit, $this->offset + 1 )
1071 ->parse();
1072 } else {
1073 $top = $this->msg( 'showingresultsnum' )
1074 ->numParams( $this->limit, $this->offset + 1, $resultsShown )
1075 ->parse();
1077 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ),
1078 Xml::tags( 'ul', null, Xml::tags( 'li', null, $top ) )
1082 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1083 $out .= Xml::closeElement( 'div' );
1085 return $out;
1089 * @param $term string
1090 * @return string
1092 protected function shortDialog( $term ) {
1093 $out = Html::hidden( 'title', $this->getTitle()->getPrefixedText() );
1094 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1095 // Term box
1096 $out .= Html::input( 'search', $term, 'search', array(
1097 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1098 'size' => '50',
1099 'autofocus',
1100 'class' => 'mw-ui-input',
1101 ) ) . "\n";
1102 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1103 $out .= Xml::submitButton(
1104 $this->msg( 'searchbutton' )->text(),
1105 array( 'class' => array( 'mw-ui-button', 'mw-ui-primary' ) )
1106 ) . "\n";
1107 return $out . $this->didYouMeanHtml;
1111 * Make a search link with some target namespaces
1113 * @param $term String
1114 * @param array $namespaces ignored
1115 * @param string $label link's text
1116 * @param string $tooltip link's tooltip
1117 * @param array $params query string parameters
1118 * @return String: HTML fragment
1120 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1121 $opt = $params;
1122 foreach ( $namespaces as $n ) {
1123 $opt['ns' . $n] = 1;
1125 $opt['redirs'] = $this->searchRedirects;
1127 $stParams = array_merge(
1128 array(
1129 'search' => $term,
1130 'fulltext' => $this->msg( 'search' )->text()
1132 $opt
1135 return Xml::element(
1136 'a',
1137 array(
1138 'href' => $this->getTitle()->getLocalURL( $stParams ),
1139 'title' => $tooltip
1141 $label
1146 * Check if query starts with image: prefix
1148 * @param string $term the string to check
1149 * @return Boolean
1151 protected function startsWithImage( $term ) {
1152 global $wgContLang;
1154 $p = explode( ':', $term );
1155 if ( count( $p ) > 1 ) {
1156 return $wgContLang->getNsIndex( $p[0] ) == NS_FILE;
1158 return false;
1162 * Check if query starts with all: prefix
1164 * @param string $term the string to check
1165 * @return Boolean
1167 protected function startsWithAll( $term ) {
1169 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1171 $p = explode( ':', $term );
1172 if ( count( $p ) > 1 ) {
1173 return $p[0] == $allkeyword;
1175 return false;
1179 * @since 1.18
1181 * @return SearchEngine
1183 public function getSearchEngine() {
1184 if ( $this->searchEngine === null ) {
1185 $this->searchEngine = $this->searchEngineType ?
1186 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1188 return $this->searchEngine;
1192 * Users of hook SpecialSearchSetupEngine can use this to
1193 * add more params to links to not lose selection when
1194 * user navigates search results.
1195 * @since 1.18
1197 * @param $key
1198 * @param $value
1200 public function setExtraParam( $key, $value ) {
1201 $this->extraParams[$key] = $value;
1204 protected function getGroupName() {
1205 return 'pages';