Support offsets in prefix searching
[mediawiki.git] / includes / specials / SpecialSearch.php
blobb1baf67db4292afd2b7d8108d190ff89703df0c3
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 'mediawiki.ui.input',
87 ) );
89 // Strip underscores from title parameter; most of the time we'll want
90 // text form here. But don't strip underscores from actual text params!
91 $titleParam = str_replace( '_', ' ', $par );
93 $request = $this->getRequest();
95 // Fetch the search term
96 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
98 $this->load();
99 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
100 $this->saveNamespaces();
101 // Remove the token from the URL to prevent the user from inadvertently
102 // exposing it (e.g. by pasting it into a public wiki page) or undoing
103 // later settings changes (e.g. by reloading the page).
104 $query = $request->getValues();
105 unset( $query['title'], $query['nsRemember'] );
106 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
107 return;
110 $this->searchEngineType = $request->getVal( 'srbackend' );
112 if ( $request->getVal( 'fulltext' )
113 || !is_null( $request->getVal( 'offset' ) )
115 $this->showResults( $search );
116 } else {
117 $this->goResult( $search );
122 * Set up basic search parameters from the request and user settings.
124 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
126 public function load() {
127 $request = $this->getRequest();
128 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
129 $this->mPrefix = $request->getVal( 'prefix', '' );
131 $user = $this->getUser();
133 # Extract manually requested namespaces
134 $nslist = $this->powerSearch( $request );
135 if ( !count( $nslist ) ) {
136 # Fallback to user preference
137 $nslist = SearchEngine::userNamespaces( $user );
140 $profile = null;
141 if ( !count( $nslist ) ) {
142 $profile = 'default';
145 $profile = $request->getVal( 'profile', $profile );
146 $profiles = $this->getSearchProfiles();
147 if ( $profile === null ) {
148 // BC with old request format
149 $profile = 'advanced';
150 foreach ( $profiles as $key => $data ) {
151 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
152 $profile = $key;
155 $this->namespaces = $nslist;
156 } elseif ( $profile === 'advanced' ) {
157 $this->namespaces = $nslist;
158 } else {
159 if ( isset( $profiles[$profile]['namespaces'] ) ) {
160 $this->namespaces = $profiles[$profile]['namespaces'];
161 } else {
162 // Unknown profile requested
163 $profile = 'default';
164 $this->namespaces = $profiles['default']['namespaces'];
168 $this->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 string $term
178 public function goResult( $term ) {
179 $this->setupPage( $term );
180 # Try to go to page as entered.
181 $title = Title::newFromText( $term );
182 # If the string cannot be used to create a title
183 if ( is_null( $title ) ) {
184 $this->showResults( $term );
186 return;
188 # If there's an exact or very near match, jump right there.
189 $title = SearchEngine::getNearMatch( $term );
191 if ( !is_null( $title ) ) {
192 $this->getOutput()->redirect( $title->getFullURL() );
194 return;
196 # No match, generate an edit URL
197 $title = Title::newFromText( $term );
198 if ( !is_null( $title ) ) {
199 wfRunHooks( 'SpecialSearchNogomatch', array( &$title ) );
201 $this->showResults( $term );
205 * @param string $term
207 public function showResults( $term ) {
208 global $wgContLang;
210 $profile = new ProfileSection( __METHOD__ );
211 $search = $this->getSearchEngine();
212 $search->setLimitOffset( $this->limit, $this->offset );
213 $search->setNamespaces( $this->namespaces );
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 ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
224 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
225 if ( $searchFowardUrl ) {
226 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
227 $out->redirect( $url );
228 } else {
229 $out->addHTML(
230 Xml::openElement( 'fieldset' ) .
231 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
232 Xml::element(
233 'p',
234 array( 'class' => 'mw-searchdisabled' ),
235 $this->msg( 'searchdisabled' )->text()
237 $this->msg( 'googlesearch' )->rawParams(
238 htmlspecialchars( $term ),
239 'UTF-8',
240 $this->msg( 'searchbutton' )->escaped()
241 )->text() .
242 Xml::closeElement( 'fieldset' )
246 return;
249 $title = Title::newFromText( $term );
250 $showSuggestion = $title === null || !$title->isKnown();
251 $search->setShowSuggestion( $showSuggestion );
253 // fetch search results
254 $rewritten = $search->replacePrefixes( $term );
256 $titleMatches = $search->searchTitle( $rewritten );
257 $textMatches = $search->searchText( $rewritten );
259 $textStatus = null;
260 if ( $textMatches instanceof Status ) {
261 $textStatus = $textMatches;
262 $textMatches = null;
265 // did you mean... suggestions
266 if ( $showSuggestion && $textMatches && !$textStatus && $textMatches->hasSuggestion() ) {
267 # mirror Go/Search behavior of original request ..
268 $didYouMeanParams = array( 'search' => $textMatches->getSuggestionQuery() );
270 if ( $this->fulltext != null ) {
271 $didYouMeanParams['fulltext'] = $this->fulltext;
274 $stParams = array_merge(
275 $didYouMeanParams,
276 $this->powerSearchOptions()
279 $suggestionSnippet = $textMatches->getSuggestionSnippet();
281 if ( $suggestionSnippet == '' ) {
282 $suggestionSnippet = null;
285 $suggestLink = Linker::linkKnown(
286 $this->getPageTitle(),
287 $suggestionSnippet,
288 array(),
289 $stParams
292 $this->didYouMeanHtml = '<div class="searchdidyoumean">'
293 . $this->msg( 'search-suggest' )->rawParams( $suggestLink )->text() . '</div>';
296 if ( !wfRunHooks( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
297 # Hook requested termination
298 return;
301 // start rendering the page
302 $out->addHtml(
303 Xml::openElement(
304 'form',
305 array(
306 'id' => ( $this->profile === 'advanced' ? 'powersearch' : 'search' ),
307 'method' => 'get',
308 'action' => wfScript(),
313 // Get number of results
314 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
315 if ( $titleMatches ) {
316 $titleMatchesNum = $titleMatches->numRows();
317 $numTitleMatches = $titleMatches->getTotalHits();
319 if ( $textMatches ) {
320 $textMatchesNum = $textMatches->numRows();
321 $numTextMatches = $textMatches->getTotalHits();
323 $num = $titleMatchesNum + $textMatchesNum;
324 $totalRes = $numTitleMatches + $numTextMatches;
326 $out->addHtml(
327 # This is an awful awful ID name. It's not a table, but we
328 # named it poorly from when this was a table so now we're
329 # stuck with it
330 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
331 $this->shortDialog( $term, $num, $totalRes ) .
332 Xml::closeElement( 'div' ) .
333 $this->formHeader( $term ) .
334 Xml::closeElement( 'form' )
337 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
338 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
339 // Empty query -- straight view of search form
340 return;
343 $out->addHtml( "<div class='searchresults'>" );
345 // prev/next links
346 $prevnext = null;
347 if ( $num || $this->offset ) {
348 // Show the create link ahead
349 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
350 if ( $totalRes > $this->limit || $this->offset ) {
351 if ( $this->searchEngineType !== null ) {
352 $this->setExtraParam( 'srbackend', $this->searchEngineType );
354 $prevnext = $this->getLanguage()->viewPrevNext(
355 $this->getPageTitle(),
356 $this->offset,
357 $this->limit,
358 $this->powerSearchOptions() + array( 'search' => $term ),
359 $this->limit + $this->offset >= $totalRes
363 wfRunHooks( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
365 $out->parserOptions()->setEditSection( false );
366 if ( $titleMatches ) {
367 if ( $numTitleMatches > 0 ) {
368 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
369 $out->addHTML( $this->showMatches( $titleMatches ) );
371 $titleMatches->free();
373 if ( $textMatches && !$textStatus ) {
374 // output appropriate heading
375 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
376 // if no title matches the heading is redundant
377 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
380 // show interwiki results if any
381 if ( $textMatches->hasInterwikiResults() ) {
382 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(), $term ) );
384 // show results
385 if ( $numTextMatches > 0 ) {
386 $out->addHTML( $this->showMatches( $textMatches ) );
389 $textMatches->free();
391 if ( $num === 0 ) {
392 if ( $textStatus ) {
393 $out->addHTML( '<div class="error">' .
394 $textStatus->getMessage( 'search-error' ) . '</div>' );
395 } else {
396 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
397 array( 'search-nonefound', wfEscapeWikiText( $term ) ) );
398 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
401 $out->addHtml( "</div>" );
403 if ( $prevnext ) {
404 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
409 * @param Title $title
410 * @param int $num The number of search results found
411 * @param null|SearchResultSet $titleMatches Results from title search
412 * @param null|SearchResultSet $textMatches Results from text search
414 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
415 // show direct page/create link if applicable
417 // Check DBkey !== '' in case of fragment link only.
418 if ( is_null( $title ) || $title->getDBkey() === ''
419 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
420 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
422 // invalid title
423 // preserve the paragraph for margins etc...
424 $this->getOutput()->addHtml( '<p></p>' );
426 return;
429 $messageName = 'searchmenu-new-nocreate';
430 $linkClass = 'mw-search-createlink';
432 if ( !$title->isExternal() ) {
433 if ( $title->isKnown() ) {
434 $messageName = 'searchmenu-exists';
435 $linkClass = 'mw-search-exists';
436 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
437 $messageName = 'searchmenu-new';
441 $params = array(
442 $messageName,
443 wfEscapeWikiText( $title->getPrefixedText() ),
444 Message::numParam( $num )
446 wfRunHooks( 'SpecialSearchCreateLink', array( $title, &$params ) );
448 // Extensions using the hook might still return an empty $messageName
449 if ( $messageName ) {
450 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
451 } else {
452 // preserve the paragraph for margins etc...
453 $this->getOutput()->addHtml( '<p></p>' );
458 * @param string $term
460 protected function setupPage( $term ) {
461 # Should advanced UI be used?
462 $this->searchAdvanced = ( $this->profile === 'advanced' );
463 $out = $this->getOutput();
464 if ( strval( $term ) !== '' ) {
465 $out->setPageTitle( $this->msg( 'searchresults' ) );
466 $out->setHTMLTitle( $this->msg( 'pagetitle' )
467 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
468 ->inContentLanguage()->text()
471 // add javascript specific to special:search
472 $out->addModules( 'mediawiki.special.search' );
476 * Extract "power search" namespace settings from the request object,
477 * returning a list of index numbers to search.
479 * @param WebRequest $request
480 * @return array
482 protected function powerSearch( &$request ) {
483 $arr = array();
484 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
485 if ( $request->getCheck( 'ns' . $ns ) ) {
486 $arr[] = $ns;
490 return $arr;
494 * Reconstruct the 'power search' options for links
496 * @return array
498 protected function powerSearchOptions() {
499 $opt = array();
500 if ( $this->profile !== 'advanced' ) {
501 $opt['profile'] = $this->profile;
502 } else {
503 foreach ( $this->namespaces as $n ) {
504 $opt['ns' . $n] = 1;
508 return $opt + $this->extraParams;
512 * Save namespace preferences when we're supposed to
514 * @return bool Whether we wrote something
516 protected function saveNamespaces() {
517 $user = $this->getUser();
518 $request = $this->getRequest();
520 if ( $user->isLoggedIn() &&
521 $user->matchEditToken(
522 $request->getVal( 'nsRemember' ),
523 'searchnamespace',
524 $request
527 // Reset namespace preferences: namespaces are not searched
528 // when they're not mentioned in the URL parameters.
529 foreach ( MWNamespace::getValidNamespaces() as $n ) {
530 $user->setOption( 'searchNs' . $n, false );
532 // The request parameters include all the namespaces to be searched.
533 // Even if they're the same as an existing profile, they're not eaten.
534 foreach ( $this->namespaces as $n ) {
535 $user->setOption( 'searchNs' . $n, true );
538 $user->saveSettings();
539 return true;
542 return false;
546 * Show whole set of results
548 * @param SearchResultSet $matches
550 * @return string
552 protected function showMatches( &$matches ) {
553 global $wgContLang;
555 $profile = new ProfileSection( __METHOD__ );
556 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
558 $out = "<ul class='mw-search-results'>\n";
559 $result = $matches->next();
560 while ( $result ) {
561 $out .= $this->showHit( $result, $terms );
562 $result = $matches->next();
564 $out .= "</ul>\n";
566 // convert the whole thing to desired language variant
567 $out = $wgContLang->convert( $out );
569 return $out;
573 * Format a single hit result
575 * @param SearchResult $result
576 * @param array $terms Terms to highlight
578 * @return string
580 protected function showHit( $result, $terms ) {
581 $profile = new ProfileSection( __METHOD__ );
583 if ( $result->isBrokenTitle() ) {
584 return '';
587 $title = $result->getTitle();
589 $titleSnippet = $result->getTitleSnippet();
591 if ( $titleSnippet == '' ) {
592 $titleSnippet = null;
595 $link_t = clone $title;
597 wfRunHooks( 'ShowSearchHitTitle',
598 array( &$link_t, &$titleSnippet, $result, $terms, $this ) );
600 $link = Linker::linkKnown(
601 $link_t,
602 $titleSnippet
605 //If page content is not readable, just return the title.
606 //This is not quite safe, but better than showing excerpts from non-readable pages
607 //Note that hiding the entry entirely would screw up paging.
608 if ( !$title->userCan( 'read', $this->getUser() ) ) {
609 return "<li>{$link}</li>\n";
612 // If the page doesn't *exist*... our search index is out of date.
613 // The least confusing at this point is to drop the result.
614 // You may get less results, but... oh well. :P
615 if ( $result->isMissingRevision() ) {
616 return '';
619 // format redirects / relevant sections
620 $redirectTitle = $result->getRedirectTitle();
621 $redirectText = $result->getRedirectSnippet();
622 $sectionTitle = $result->getSectionTitle();
623 $sectionText = $result->getSectionSnippet();
624 $categorySnippet = $result->getCategorySnippet();
626 $redirect = '';
627 if ( !is_null( $redirectTitle ) ) {
628 if ( $redirectText == '' ) {
629 $redirectText = null;
632 $redirect = "<span class='searchalttitle'>" .
633 $this->msg( 'search-redirect' )->rawParams(
634 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
635 "</span>";
638 $section = '';
639 if ( !is_null( $sectionTitle ) ) {
640 if ( $sectionText == '' ) {
641 $sectionText = null;
644 $section = "<span class='searchalttitle'>" .
645 $this->msg( 'search-section' )->rawParams(
646 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
647 "</span>";
650 $category = '';
651 if ( $categorySnippet ) {
652 $category = "<span class='searchalttitle'>" .
653 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
654 "</span>";
657 // format text extract
658 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
660 $lang = $this->getLanguage();
662 // format description
663 $byteSize = $result->getByteSize();
664 $wordCount = $result->getWordCount();
665 $timestamp = $result->getTimestamp();
666 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
667 ->numParams( $wordCount )->escaped();
669 if ( $title->getNamespace() == NS_CATEGORY ) {
670 $cat = Category::newFromTitle( $title );
671 $size = $this->msg( 'search-result-category-size' )
672 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
673 ->escaped();
676 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
678 $fileMatch = '';
679 // Include a thumbnail for media files...
680 if ( $title->getNamespace() == NS_FILE ) {
681 $img = $result->getFile();
682 $img = $img ?: wfFindFile( $title );
683 if ( $result->isFileMatch() ) {
684 $fileMatch = "<span class='searchalttitle'>" .
685 $this->msg( 'search-file-match' )->escaped() . "</span>";
687 if ( $img ) {
688 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
689 if ( $thumb ) {
690 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
691 // Float doesn't seem to interact well with the bullets.
692 // Table messes up vertical alignment of the bullets.
693 // Bullets are therefore disabled (didn't look great anyway).
694 return "<li>" .
695 '<table class="searchResultImage">' .
696 '<tr>' .
697 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
698 $thumb->toHtml( array( 'desc-link' => true ) ) .
699 '</td>' .
700 '<td style="vertical-align: top;">' .
701 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
702 $extract .
703 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
704 '</td>' .
705 '</tr>' .
706 '</table>' .
707 "</li>\n";
712 $html = null;
714 $score = '';
715 if ( wfRunHooks( 'ShowSearchHit', array(
716 $this, $result, $terms,
717 &$link, &$redirect, &$section, &$extract,
718 &$score, &$size, &$date, &$related,
719 &$html
720 ) ) ) {
721 $html = "<li><div class='mw-search-result-heading'>" .
722 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
723 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
724 "</li>\n";
727 return $html;
731 * Show results from other wikis
733 * @param SearchResultSet|array $matches
734 * @param string $query
736 * @return string
738 protected function showInterwiki( $matches, $query ) {
739 global $wgContLang;
740 $profile = new ProfileSection( __METHOD__ );
742 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
743 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
744 $out .= "<ul class='mw-search-iwresults'>\n";
746 // work out custom project captions
747 $customCaptions = array();
748 // format per line <iwprefix>:<caption>
749 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
750 foreach ( $customLines as $line ) {
751 $parts = explode( ":", $line, 2 );
752 if ( count( $parts ) == 2 ) { // validate line
753 $customCaptions[$parts[0]] = $parts[1];
757 if ( !is_array( $matches ) ) {
758 $matches = array( $matches );
761 foreach ( $matches as $set ) {
762 $prev = null;
763 $result = $set->next();
764 while ( $result ) {
765 $out .= $this->showInterwikiHit( $result, $prev, $query, $customCaptions );
766 $prev = $result->getInterwikiPrefix();
767 $result = $set->next();
771 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
772 $out .= "</ul></div>\n";
774 // convert the whole thing to desired language variant
775 $out = $wgContLang->convert( $out );
777 return $out;
781 * Show single interwiki link
783 * @param SearchResult $result
784 * @param string $lastInterwiki
785 * @param string $query
786 * @param array $customCaptions Interwiki prefix -> caption
788 * @return string
790 protected function showInterwikiHit( $result, $lastInterwiki, $query, $customCaptions ) {
791 $profile = new ProfileSection( __METHOD__ );
793 if ( $result->isBrokenTitle() ) {
794 return '';
797 $title = $result->getTitle();
799 $titleSnippet = $result->getTitleSnippet();
801 if ( $titleSnippet == '' ) {
802 $titleSnippet = null;
805 $link = Linker::linkKnown(
806 $title,
807 $titleSnippet
810 // format redirect if any
811 $redirectTitle = $result->getRedirectTitle();
812 $redirectText = $result->getRedirectSnippet();
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 != $title->getInterwiki() ) {
828 if ( array_key_exists( $title->getInterwiki(), $customCaptions ) ) {
829 // captions from 'search-interwiki-custom'
830 $caption = $customCaptions[$title->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( $title->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( $title->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";
854 return $out;
858 * Generates the power search box at [[Special:Search]]
860 * @param string $term Search term
861 * @param array $opts
862 * @return string HTML form
864 protected function powerSearchBox( $term, $opts ) {
865 global $wgContLang;
867 // Groups namespaces into rows according to subject
868 $rows = array();
869 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
870 $subject = MWNamespace::getSubject( $namespace );
871 if ( !array_key_exists( $subject, $rows ) ) {
872 $rows[$subject] = "";
875 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
876 if ( $name == '' ) {
877 $name = $this->msg( 'blanknamespace' )->text();
880 $rows[$subject] .=
881 Xml::openElement( 'td' ) .
882 Xml::checkLabel(
883 $name,
884 "ns{$namespace}",
885 "mw-search-ns{$namespace}",
886 in_array( $namespace, $this->namespaces )
888 Xml::closeElement( 'td' );
891 $rows = array_values( $rows );
892 $numRows = count( $rows );
894 // Lays out namespaces in multiple floating two-column tables so they'll
895 // be arranged nicely while still accommodating different screen widths
896 $namespaceTables = '';
897 for ( $i = 0; $i < $numRows; $i += 4 ) {
898 $namespaceTables .= Xml::openElement( 'table' );
900 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
901 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
904 $namespaceTables .= Xml::closeElement( 'table' );
907 $showSections = array( 'namespaceTables' => $namespaceTables );
909 wfRunHooks( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
911 $hidden = '';
912 foreach ( $opts as $key => $value ) {
913 $hidden .= Html::hidden( $key, $value );
916 # Stuff to feed saveNamespaces()
917 $remember = '';
918 $user = $this->getUser();
919 if ( $user->isLoggedIn() ) {
920 $remember .= Xml::checkLabel(
921 wfMessage( 'powersearch-remember' )->text(),
922 'nsRemember',
923 'mw-search-powersearch-remember',
924 false,
925 // The token goes here rather than in a hidden field so it
926 // is only sent when necessary (not every form submission).
927 array( 'value' => $user->getEditToken(
928 'searchnamespace',
929 $this->getRequest()
934 // Return final output
935 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
936 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
937 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
938 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
939 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
940 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
941 $hidden .
942 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
943 $remember .
944 Xml::closeElement( 'fieldset' );
948 * @return array
950 protected function getSearchProfiles() {
951 // Builds list of Search Types (profiles)
952 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
954 $profiles = array(
955 'default' => array(
956 'message' => 'searchprofile-articles',
957 'tooltip' => 'searchprofile-articles-tooltip',
958 'namespaces' => SearchEngine::defaultNamespaces(),
959 'namespace-messages' => SearchEngine::namespacesAsText(
960 SearchEngine::defaultNamespaces()
963 'images' => array(
964 'message' => 'searchprofile-images',
965 'tooltip' => 'searchprofile-images-tooltip',
966 'namespaces' => array( NS_FILE ),
968 'all' => array(
969 'message' => 'searchprofile-everything',
970 'tooltip' => 'searchprofile-everything-tooltip',
971 'namespaces' => $nsAllSet,
973 'advanced' => array(
974 'message' => 'searchprofile-advanced',
975 'tooltip' => 'searchprofile-advanced-tooltip',
976 'namespaces' => self::NAMESPACES_CURRENT,
980 wfRunHooks( 'SpecialSearchProfiles', array( &$profiles ) );
982 foreach ( $profiles as &$data ) {
983 if ( !is_array( $data['namespaces'] ) ) {
984 continue;
986 sort( $data['namespaces'] );
989 return $profiles;
993 * @param string $term
994 * @return string
996 protected function formHeader( $term ) {
997 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-formheader' ) );
999 $bareterm = $term;
1000 if ( $this->startsWithImage( $term ) ) {
1001 // Deletes prefixes
1002 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1005 $profiles = $this->getSearchProfiles();
1006 $lang = $this->getLanguage();
1008 // Outputs XML for Search Types
1009 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1010 $out .= Xml::openElement( 'ul' );
1011 foreach ( $profiles as $id => $profile ) {
1012 if ( !isset( $profile['parameters'] ) ) {
1013 $profile['parameters'] = array();
1015 $profile['parameters']['profile'] = $id;
1017 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1018 $lang->commaList( $profile['namespace-messages'] ) : null;
1019 $out .= Xml::tags(
1020 'li',
1021 array(
1022 'class' => $this->profile === $id ? 'current' : 'normal'
1024 $this->makeSearchLink(
1025 $bareterm,
1026 array(),
1027 $this->msg( $profile['message'] )->text(),
1028 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1029 $profile['parameters']
1033 $out .= Xml::closeElement( 'ul' );
1034 $out .= Xml::closeElement( 'div' );
1035 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1036 $out .= Xml::closeElement( 'div' );
1038 // Hidden stuff
1039 $opts = array();
1040 $opts['profile'] = $this->profile;
1042 if ( $this->profile === 'advanced' ) {
1043 $out .= $this->powerSearchBox( $term, $opts );
1044 } else {
1045 $form = '';
1046 wfRunHooks( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1047 $out .= $form;
1050 return $out;
1054 * @param string $term
1055 * @param int $resultsShown
1056 * @param int $totalNum
1057 * @return string
1059 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1060 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1061 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1062 // Term box
1063 $out .= Html::input( 'search', $term, 'search', array(
1064 'id' => $this->profile === 'advanced' ? 'powerSearchText' : 'searchText',
1065 'size' => '50',
1066 'autofocus',
1067 'class' => 'mw-ui-input mw-ui-input-inline',
1068 ) ) . "\n";
1069 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1070 $out .= Html::submitButton(
1071 $this->msg( 'searchbutton' )->text(),
1072 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1073 array( 'mw-ui-progressive' )
1074 ) . "\n";
1076 // Results-info
1077 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1078 $top = $this->msg( 'search-showingresults' )
1079 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1080 ->numParams( $resultsShown )
1081 ->parse();
1082 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1083 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1086 return $out . $this->didYouMeanHtml;
1090 * Make a search link with some target namespaces
1092 * @param string $term
1093 * @param array $namespaces Ignored
1094 * @param string $label Link's text
1095 * @param string $tooltip Link's tooltip
1096 * @param array $params Query string parameters
1097 * @return string HTML fragment
1099 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1100 $opt = $params;
1101 foreach ( $namespaces as $n ) {
1102 $opt['ns' . $n] = 1;
1105 $stParams = array_merge(
1106 array(
1107 'search' => $term,
1108 'fulltext' => $this->msg( 'search' )->text()
1110 $opt
1113 return Xml::element(
1114 'a',
1115 array(
1116 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1117 'title' => $tooltip
1119 $label
1124 * Check if query starts with image: prefix
1126 * @param string $term The string to check
1127 * @return bool
1129 protected function startsWithImage( $term ) {
1130 global $wgContLang;
1132 $parts = explode( ':', $term );
1133 if ( count( $parts ) > 1 ) {
1134 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1137 return false;
1141 * Check if query starts with all: prefix
1143 * @param string $term The string to check
1144 * @return bool
1146 protected function startsWithAll( $term ) {
1148 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1150 $parts = explode( ':', $term );
1151 if ( count( $parts ) > 1 ) {
1152 return $parts[0] == $allkeyword;
1155 return false;
1159 * @since 1.18
1161 * @return SearchEngine
1163 public function getSearchEngine() {
1164 if ( $this->searchEngine === null ) {
1165 $this->searchEngine = $this->searchEngineType ?
1166 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1169 return $this->searchEngine;
1173 * Current search profile.
1174 * @return null|string
1176 function getProfile() {
1177 return $this->profile;
1181 * Current namespaces.
1182 * @return array
1184 function getNamespaces() {
1185 return $this->namespaces;
1189 * Users of hook SpecialSearchSetupEngine can use this to
1190 * add more params to links to not lose selection when
1191 * user navigates search results.
1192 * @since 1.18
1194 * @param string $key
1195 * @param mixed $value
1197 public function setExtraParam( $key, $value ) {
1198 $this->extraParams[$key] = $value;
1201 protected function getGroupName() {
1202 return 'pages';