Displaying search results for multiple wikis
[lhc/web/wiklou.git] / includes / specials / SpecialSearch.php
1 <?php
2 /**
3 * Implements Special:Search
4 *
5 * Copyright © 2004 Brion Vibber <brion@pobox.com>
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 * @ingroup SpecialPage
24 */
25
26 /**
27 * implements Special:Search - Run text & title search and display the output
28 * @ingroup SpecialPage
29 */
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
38 */
39 protected $profile;
40
41 /** @var SearchEngine Search engine */
42 protected $searchEngine;
43
44 /** @var string Search engine type, if not default */
45 protected $searchEngineType;
46
47 /** @var array For links */
48 protected $extraParams = array();
49
50 /**
51 * @var string The prefix url parameter. Set on the searcher and the
52 * is expected to treat it as prefix filter on titles.
53 */
54 protected $mPrefix;
55
56 /**
57 * @var int
58 */
59 protected $limit, $offset;
60
61 /**
62 * @var array
63 */
64 protected $namespaces;
65
66 /**
67 * @var string
68 */
69 protected $fulltext;
70
71 /**
72 * @var bool
73 */
74 protected $runSuggestion = true;
75
76 /**
77 * Names of the wikis, in format: Interwiki prefix -> caption
78 * @var array
79 */
80 protected $customCaptions;
81
82 const NAMESPACES_CURRENT = 'sense';
83
84 public function __construct() {
85 parent::__construct( 'Search' );
86 }
87
88 /**
89 * Entry point
90 *
91 * @param string $par
92 */
93 public function execute( $par ) {
94 $this->setHeaders();
95 $this->outputHeader();
96 $out = $this->getOutput();
97 $out->allowClickjacking();
98 $out->addModuleStyles( array(
99 'mediawiki.special', 'mediawiki.special.search', 'mediawiki.ui', 'mediawiki.ui.button',
100 'mediawiki.ui.input',
101 ) );
102
103 // Strip underscores from title parameter; most of the time we'll want
104 // text form here. But don't strip underscores from actual text params!
105 $titleParam = str_replace( '_', ' ', $par );
106
107 $request = $this->getRequest();
108
109 // Fetch the search term
110 $search = str_replace( "\n", " ", $request->getText( 'search', $titleParam ) );
111
112 $this->load();
113 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
114 $this->saveNamespaces();
115 // Remove the token from the URL to prevent the user from inadvertently
116 // exposing it (e.g. by pasting it into a public wiki page) or undoing
117 // later settings changes (e.g. by reloading the page).
118 $query = $request->getValues();
119 unset( $query['title'], $query['nsRemember'] );
120 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
121 return;
122 }
123
124 $out->addJsConfigVars( array( 'searchTerm' => $search ) );
125 $this->searchEngineType = $request->getVal( 'srbackend' );
126
127 if ( $request->getVal( 'fulltext' )
128 || !is_null( $request->getVal( 'offset' ) )
129 ) {
130 $this->showResults( $search );
131 } else {
132 $this->goResult( $search );
133 }
134 }
135
136 /**
137 * Set up basic search parameters from the request and user settings.
138 *
139 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
140 */
141 public function load() {
142 $request = $this->getRequest();
143 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
144 $this->mPrefix = $request->getVal( 'prefix', '' );
145
146 $user = $this->getUser();
147
148 # Extract manually requested namespaces
149 $nslist = $this->powerSearch( $request );
150 if ( !count( $nslist ) ) {
151 # Fallback to user preference
152 $nslist = SearchEngine::userNamespaces( $user );
153 }
154
155 $profile = null;
156 if ( !count( $nslist ) ) {
157 $profile = 'default';
158 }
159
160 $profile = $request->getVal( 'profile', $profile );
161 $profiles = $this->getSearchProfiles();
162 if ( $profile === null ) {
163 // BC with old request format
164 $profile = 'advanced';
165 foreach ( $profiles as $key => $data ) {
166 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
167 $profile = $key;
168 }
169 }
170 $this->namespaces = $nslist;
171 } elseif ( $profile === 'advanced' ) {
172 $this->namespaces = $nslist;
173 } else {
174 if ( isset( $profiles[$profile]['namespaces'] ) ) {
175 $this->namespaces = $profiles[$profile]['namespaces'];
176 } else {
177 // Unknown profile requested
178 $profile = 'default';
179 $this->namespaces = $profiles['default']['namespaces'];
180 }
181 }
182
183 $this->fulltext = $request->getVal( 'fulltext' );
184 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
185 $this->profile = $profile;
186 }
187
188 /**
189 * If an exact title match can be found, jump straight ahead to it.
190 *
191 * @param string $term
192 */
193 public function goResult( $term ) {
194 $this->setupPage( $term );
195 # Try to go to page as entered.
196 $title = Title::newFromText( $term );
197 # If the string cannot be used to create a title
198 if ( is_null( $title ) ) {
199 $this->showResults( $term );
200
201 return;
202 }
203 # If there's an exact or very near match, jump right there.
204 $title = SearchEngine::getNearMatch( $term );
205
206 if ( !is_null( $title ) ) {
207 $this->getOutput()->redirect( $title->getFullURL() );
208
209 return;
210 }
211 # No match, generate an edit URL
212 $title = Title::newFromText( $term );
213 if ( !is_null( $title ) ) {
214 Hooks::run( 'SpecialSearchNogomatch', array( &$title ) );
215 }
216 $this->showResults( $term );
217 }
218
219 /**
220 * @param string $term
221 */
222 public function showResults( $term ) {
223 global $wgContLang;
224
225 $search = $this->getSearchEngine();
226 $search->setFeatureData( 'rewrite', $this->runSuggestion );
227 $search->setLimitOffset( $this->limit, $this->offset );
228 $search->setNamespaces( $this->namespaces );
229 $search->prefix = $this->mPrefix;
230 $term = $search->transformSearchTerm( $term );
231
232 Hooks::run( 'SpecialSearchSetupEngine', array( $this, $this->profile, $search ) );
233
234 $this->setupPage( $term );
235
236 $out = $this->getOutput();
237
238 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
239 $searchFowardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
240 if ( $searchFowardUrl ) {
241 $url = str_replace( '$1', urlencode( $term ), $searchFowardUrl );
242 $out->redirect( $url );
243 } else {
244 $out->addHTML(
245 Xml::openElement( 'fieldset' ) .
246 Xml::element( 'legend', null, $this->msg( 'search-external' )->text() ) .
247 Xml::element(
248 'p',
249 array( 'class' => 'mw-searchdisabled' ),
250 $this->msg( 'searchdisabled' )->text()
251 ) .
252 $this->msg( 'googlesearch' )->rawParams(
253 htmlspecialchars( $term ),
254 'UTF-8',
255 $this->msg( 'searchbutton' )->escaped()
256 )->text() .
257 Xml::closeElement( 'fieldset' )
258 );
259 }
260
261 return;
262 }
263
264 $title = Title::newFromText( $term );
265 $showSuggestion = $title === null || !$title->isKnown();
266 $search->setShowSuggestion( $showSuggestion );
267
268 // fetch search results
269 $rewritten = $search->replacePrefixes( $term );
270
271 $titleMatches = $search->searchTitle( $rewritten );
272 $textMatches = $search->searchText( $rewritten );
273
274 $textStatus = null;
275 if ( $textMatches instanceof Status ) {
276 $textStatus = $textMatches;
277 $textMatches = null;
278 }
279
280 // did you mean... suggestions
281 $didYouMeanHtml = '';
282 if ( $showSuggestion && $textMatches && !$textStatus ) {
283 if ( $textMatches->hasRewrittenQuery() ) {
284 $didYouMeanHtml = $this->getDidYouMeanRewrittenHtml( $term, $textMatches );
285 } elseif ( $textMatches->hasSuggestion() ) {
286 $didYouMeanHtml = $this->getDidYouMeanHtml( $textMatches );
287 }
288 }
289
290 if ( !Hooks::run( 'SpecialSearchResultsPrepend', array( $this, $out, $term ) ) ) {
291 # Hook requested termination
292 return;
293 }
294
295 // start rendering the page
296 $out->addHtml(
297 Xml::openElement(
298 'form',
299 array(
300 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
301 'method' => 'get',
302 'action' => wfScript(),
303 )
304 )
305 );
306
307 // Get number of results
308 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
309 if ( $titleMatches ) {
310 $titleMatchesNum = $titleMatches->numRows();
311 $numTitleMatches = $titleMatches->getTotalHits();
312 }
313 if ( $textMatches ) {
314 $textMatchesNum = $textMatches->numRows();
315 $numTextMatches = $textMatches->getTotalHits();
316 }
317 $num = $titleMatchesNum + $textMatchesNum;
318 $totalRes = $numTitleMatches + $numTextMatches;
319
320 $out->addHtml(
321 # This is an awful awful ID name. It's not a table, but we
322 # named it poorly from when this was a table so now we're
323 # stuck with it
324 Xml::openElement( 'div', array( 'id' => 'mw-search-top-table' ) ) .
325 $this->shortDialog( $term, $num, $totalRes ) .
326 Xml::closeElement( 'div' ) .
327 $this->searchProfileTabs( $term ) .
328 $this->searchOptions( $term ) .
329 Xml::closeElement( 'form' ) .
330 $didYouMeanHtml
331 );
332
333 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
334 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
335 // Empty query -- straight view of search form
336 return;
337 }
338
339 $out->addHtml( "<div class='searchresults'>" );
340
341 // prev/next links
342 $prevnext = null;
343 if ( $num || $this->offset ) {
344 // Show the create link ahead
345 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
346 if ( $totalRes > $this->limit || $this->offset ) {
347 if ( $this->searchEngineType !== null ) {
348 $this->setExtraParam( 'srbackend', $this->searchEngineType );
349 }
350 $prevnext = $this->getLanguage()->viewPrevNext(
351 $this->getPageTitle(),
352 $this->offset,
353 $this->limit,
354 $this->powerSearchOptions() + array( 'search' => $term ),
355 $this->limit + $this->offset >= $totalRes
356 );
357 }
358 }
359 Hooks::run( 'SpecialSearchResults', array( $term, &$titleMatches, &$textMatches ) );
360
361 $out->parserOptions()->setEditSection( false );
362 if ( $titleMatches ) {
363 if ( $numTitleMatches > 0 ) {
364 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
365 $out->addHTML( $this->showMatches( $titleMatches ) );
366 }
367 $titleMatches->free();
368 }
369 if ( $textMatches && !$textStatus ) {
370 // output appropriate heading
371 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
372 // if no title matches the heading is redundant
373 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
374 }
375
376 // show results
377 if ( $numTextMatches > 0 ) {
378 $out->addHTML( $this->showMatches( $textMatches ) );
379 }
380
381 // show secondary interwiki results if any
382 if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
383 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
384 SearchResultSet::SECONDARY_RESULTS ), $term ) );
385 }
386
387 $textMatches->free();
388 }
389
390 $hasOtherResults = $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
391
392 if ( $num === 0 ) {
393 if ( $textStatus ) {
394 $out->addHTML( '<div class="error">' .
395 $textStatus->getMessage( 'search-error' ) . '</div>' );
396 } else {
397 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
398 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
399 array( $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
400 wfEscapeWikiText( $term )
401 ) );
402 }
403 }
404
405 if ( $hasOtherResults ) {
406 foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
407 as $interwiki => $interwikiResult ) {
408 if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
409 // ignore bad interwikis for now
410 continue;
411 }
412 // TODO: wiki header
413 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
414 }
415 }
416
417 $out->addHTML( '<div class="visualClear"></div>' );
418
419 if ( $prevnext ) {
420 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
421 }
422
423 $out->addHtml( "</div>" );
424
425 Hooks::run( 'SpecialSearchResultsAppend', array( $this, $out, $term ) );
426
427 }
428
429 /**
430 * Produce wiki header for interwiki results
431 * @param string $interwiki Interwiki name
432 * @param SearchResultSet $interwikiResult The result set
433 */
434 protected function interwikiHeader( $interwiki, $interwikiResult ) {
435 // TODO: we need to figure out how to name wikis correctly
436 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
437 return "<p class=\"mw-search-interwiki-header\">\n$wikiMsg</p>";
438 }
439
440 /**
441 * Decide if the suggested query should be run, and it's results returned
442 * instead of the provided $textMatches
443 *
444 * @param SearchResultSet $textMatches The results of a users query
445 * @return bool
446 */
447 protected function shouldRunSuggestedQuery( SearchResultSet $textMatches ) {
448 if ( !$this->runSuggestion ||
449 !$textMatches->hasSuggestion() ||
450 $textMatches->numRows() > 0 ||
451 $textMatches->searchContainedSyntax()
452 ) {
453 return false;
454 }
455
456 return $this->getConfig()->get( 'SearchRunSuggestedQuery' );
457 }
458
459 /**
460 * Generates HTML shown to the user when we have a suggestion about a query
461 * that might give more results than their current query.
462 */
463 protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
464 # mirror Go/Search behavior of original request ..
465 $params = array( 'search' => $textMatches->getSuggestionQuery() );
466 if ( $this->fulltext != null ) {
467 $params['fulltext'] = $this->fulltext;
468 }
469 $stParams = array_merge( $params, $this->powerSearchOptions() );
470
471 $suggest = Linker::linkKnown(
472 $this->getPageTitle(),
473 $textMatches->getSuggestionSnippet() ?: null,
474 array( 'id' => 'mw-search-DYM-suggestion' ),
475 $stParams
476 );
477
478 # HTML of did you mean... search suggestion link
479 return Html::rawElement(
480 'div',
481 array( 'class' => 'searchdidyoumean' ),
482 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
483 );
484 }
485
486 /**
487 * Generates HTML shown to user when their query has been internally rewritten,
488 * and the results of the rewritten query are being returned.
489 *
490 * @param string $term The users search input
491 * @param SearchResultSet $textMatches The response to the users initial search request
492 * @return string HTML linking the user to their original $term query, and the one
493 * suggested by $textMatches.
494 */
495 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
496 // Showing results for '$rewritten'
497 // Search instead for '$orig'
498
499 $params = array( 'search' => $textMatches->getQueryAfterRewrite() );
500 if ( $this->fulltext != null ) {
501 $params['fulltext'] = $this->fulltext;
502 }
503 $stParams = array_merge( $params, $this->powerSearchOptions() );
504
505 $rewritten = Linker::linkKnown(
506 $this->getPageTitle(),
507 $textMatches->getQueryAfterRewriteSnippet() ?: null,
508 array( 'id' => 'mw-search-DYM-rewritten' ),
509 $stParams
510 );
511
512 $stParams['search'] = $term;
513 $stParams['runsuggestion'] = 0;
514 $original = Linker::linkKnown(
515 $this->getPageTitle(),
516 htmlspecialchars( $term ),
517 array( 'id' => 'mw-search-DYM-original' ),
518 $stParams
519 );
520
521 return Html::rawElement(
522 'div',
523 array( 'class' => 'searchdidyoumean' ),
524 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
525 );
526 }
527
528 /**
529 * @param Title $title
530 * @param int $num The number of search results found
531 * @param null|SearchResultSet $titleMatches Results from title search
532 * @param null|SearchResultSet $textMatches Results from text search
533 */
534 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
535 // show direct page/create link if applicable
536
537 // Check DBkey !== '' in case of fragment link only.
538 if ( is_null( $title ) || $title->getDBkey() === ''
539 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
540 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
541 ) {
542 // invalid title
543 // preserve the paragraph for margins etc...
544 $this->getOutput()->addHtml( '<p></p>' );
545
546 return;
547 }
548
549 $messageName = 'searchmenu-new-nocreate';
550 $linkClass = 'mw-search-createlink';
551
552 if ( !$title->isExternal() ) {
553 if ( $title->isKnown() ) {
554 $messageName = 'searchmenu-exists';
555 $linkClass = 'mw-search-exists';
556 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
557 $messageName = 'searchmenu-new';
558 }
559 }
560
561 $params = array(
562 $messageName,
563 wfEscapeWikiText( $title->getPrefixedText() ),
564 Message::numParam( $num )
565 );
566 Hooks::run( 'SpecialSearchCreateLink', array( $title, &$params ) );
567
568 // Extensions using the hook might still return an empty $messageName
569 if ( $messageName ) {
570 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
571 } else {
572 // preserve the paragraph for margins etc...
573 $this->getOutput()->addHtml( '<p></p>' );
574 }
575 }
576
577 /**
578 * @param string $term
579 */
580 protected function setupPage( $term ) {
581 $out = $this->getOutput();
582 if ( strval( $term ) !== '' ) {
583 $out->setPageTitle( $this->msg( 'searchresults' ) );
584 $out->setHTMLTitle( $this->msg( 'pagetitle' )
585 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
586 ->inContentLanguage()->text()
587 );
588 }
589 // add javascript specific to special:search
590 $out->addModules( 'mediawiki.special.search' );
591 }
592
593 /**
594 * Return true if current search is a power (advanced) search
595 *
596 * @return bool
597 */
598 protected function isPowerSearch() {
599 return $this->profile === 'advanced';
600 }
601
602 /**
603 * Extract "power search" namespace settings from the request object,
604 * returning a list of index numbers to search.
605 *
606 * @param WebRequest $request
607 * @return array
608 */
609 protected function powerSearch( &$request ) {
610 $arr = array();
611 foreach ( SearchEngine::searchableNamespaces() as $ns => $name ) {
612 if ( $request->getCheck( 'ns' . $ns ) ) {
613 $arr[] = $ns;
614 }
615 }
616
617 return $arr;
618 }
619
620 /**
621 * Reconstruct the 'power search' options for links
622 *
623 * @return array
624 */
625 protected function powerSearchOptions() {
626 $opt = array();
627 if ( !$this->isPowerSearch() ) {
628 $opt['profile'] = $this->profile;
629 } else {
630 foreach ( $this->namespaces as $n ) {
631 $opt['ns' . $n] = 1;
632 }
633 }
634
635 return $opt + $this->extraParams;
636 }
637
638 /**
639 * Save namespace preferences when we're supposed to
640 *
641 * @return bool Whether we wrote something
642 */
643 protected function saveNamespaces() {
644 $user = $this->getUser();
645 $request = $this->getRequest();
646
647 if ( $user->isLoggedIn() &&
648 $user->matchEditToken(
649 $request->getVal( 'nsRemember' ),
650 'searchnamespace',
651 $request
652 ) && !wfReadOnly()
653 ) {
654 // Reset namespace preferences: namespaces are not searched
655 // when they're not mentioned in the URL parameters.
656 foreach ( MWNamespace::getValidNamespaces() as $n ) {
657 $user->setOption( 'searchNs' . $n, false );
658 }
659 // The request parameters include all the namespaces to be searched.
660 // Even if they're the same as an existing profile, they're not eaten.
661 foreach ( $this->namespaces as $n ) {
662 $user->setOption( 'searchNs' . $n, true );
663 }
664
665 $user->saveSettings();
666 return true;
667 }
668
669 return false;
670 }
671
672 /**
673 * Show whole set of results
674 *
675 * @param SearchResultSet $matches
676 * @param string $interwiki Interwiki name
677 *
678 * @return string
679 */
680 protected function showMatches( &$matches, $interwiki = null ) {
681 global $wgContLang;
682
683 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
684 $out = '';
685 $result = $matches->next();
686 $pos = $this->offset;
687
688 if ( $result && $interwiki ) {
689 $out .= $this->interwikiHeader( $interwiki, $result );
690 }
691
692 $out .= "<ul class='mw-search-results'>\n";
693 while ( $result ) {
694 $out .= $this->showHit( $result, $terms, ++$pos );
695 $result = $matches->next();
696 }
697 $out .= "</ul>\n";
698
699 // convert the whole thing to desired language variant
700 $out = $wgContLang->convert( $out );
701
702 return $out;
703 }
704
705 /**
706 * Format a single hit result
707 *
708 * @param SearchResult $result
709 * @param array $terms Terms to highlight
710 * @param int $position Position within the search results, including offset.
711 *
712 * @return string
713 */
714 protected function showHit( $result, $terms, $position ) {
715
716 if ( $result->isBrokenTitle() ) {
717 return '';
718 }
719
720 $title = $result->getTitle();
721
722 $titleSnippet = $result->getTitleSnippet();
723
724 if ( $titleSnippet == '' ) {
725 $titleSnippet = null;
726 }
727
728 $link_t = clone $title;
729 $query = array();
730
731 Hooks::run( 'ShowSearchHitTitle',
732 array( &$link_t, &$titleSnippet, $result, $terms, $this, &$query ) );
733
734 $link = Linker::linkKnown(
735 $link_t,
736 $titleSnippet,
737 array( 'data-serp-pos' => $position ), // HTML attributes
738 $query
739 );
740
741 // If page content is not readable, just return the title.
742 // This is not quite safe, but better than showing excerpts from non-readable pages
743 // Note that hiding the entry entirely would screw up paging.
744 if ( !$title->userCan( 'read', $this->getUser() ) ) {
745 return "<li>{$link}</li>\n";
746 }
747
748 // If the page doesn't *exist*... our search index is out of date.
749 // The least confusing at this point is to drop the result.
750 // You may get less results, but... oh well. :P
751 if ( $result->isMissingRevision() ) {
752 return '';
753 }
754
755 // format redirects / relevant sections
756 $redirectTitle = $result->getRedirectTitle();
757 $redirectText = $result->getRedirectSnippet();
758 $sectionTitle = $result->getSectionTitle();
759 $sectionText = $result->getSectionSnippet();
760 $categorySnippet = $result->getCategorySnippet();
761
762 $redirect = '';
763 if ( !is_null( $redirectTitle ) ) {
764 if ( $redirectText == '' ) {
765 $redirectText = null;
766 }
767
768 $redirect = "<span class='searchalttitle'>" .
769 $this->msg( 'search-redirect' )->rawParams(
770 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
771 "</span>";
772 }
773
774 $section = '';
775 if ( !is_null( $sectionTitle ) ) {
776 if ( $sectionText == '' ) {
777 $sectionText = null;
778 }
779
780 $section = "<span class='searchalttitle'>" .
781 $this->msg( 'search-section' )->rawParams(
782 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
783 "</span>";
784 }
785
786 $category = '';
787 if ( $categorySnippet ) {
788 $category = "<span class='searchalttitle'>" .
789 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
790 "</span>";
791 }
792
793 // format text extract
794 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
795
796 $lang = $this->getLanguage();
797
798 // format description
799 $byteSize = $result->getByteSize();
800 $wordCount = $result->getWordCount();
801 $timestamp = $result->getTimestamp();
802 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
803 ->numParams( $wordCount )->escaped();
804
805 if ( $title->getNamespace() == NS_CATEGORY ) {
806 $cat = Category::newFromTitle( $title );
807 $size = $this->msg( 'search-result-category-size' )
808 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
809 ->escaped();
810 }
811
812 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
813
814 $fileMatch = '';
815 // Include a thumbnail for media files...
816 if ( $title->getNamespace() == NS_FILE ) {
817 $img = $result->getFile();
818 $img = $img ?: wfFindFile( $title );
819 if ( $result->isFileMatch() ) {
820 $fileMatch = "<span class='searchalttitle'>" .
821 $this->msg( 'search-file-match' )->escaped() . "</span>";
822 }
823 if ( $img ) {
824 $thumb = $img->transform( array( 'width' => 120, 'height' => 120 ) );
825 if ( $thumb ) {
826 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
827 // Float doesn't seem to interact well with the bullets.
828 // Table messes up vertical alignment of the bullets.
829 // Bullets are therefore disabled (didn't look great anyway).
830 return "<li>" .
831 '<table class="searchResultImage">' .
832 '<tr>' .
833 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
834 $thumb->toHtml( array( 'desc-link' => true ) ) .
835 '</td>' .
836 '<td style="vertical-align: top;">' .
837 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
838 $extract .
839 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
840 '</td>' .
841 '</tr>' .
842 '</table>' .
843 "</li>\n";
844 }
845 }
846 }
847
848 $html = null;
849
850 $score = '';
851 if ( Hooks::run( 'ShowSearchHit', array(
852 $this, $result, $terms,
853 &$link, &$redirect, &$section, &$extract,
854 &$score, &$size, &$date, &$related,
855 &$html
856 ) ) ) {
857 $html = "<li><div class='mw-search-result-heading'>" .
858 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
859 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
860 "</li>\n";
861 }
862
863 return $html;
864 }
865
866 /**
867 * Extract custom captions from search-interwiki-custom message
868 */
869 protected function getCustomCaptions() {
870 if ( is_null( $this->customCaptions ) ) {
871 $this->customCaptions = array();
872 // format per line <iwprefix>:<caption>
873 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
874 foreach ( $customLines as $line ) {
875 $parts = explode( ":", $line, 2 );
876 if ( count( $parts ) == 2 ) { // validate line
877 $this->customCaptions[$parts[0]] = $parts[1];
878 }
879 }
880 }
881 }
882
883 /**
884 * Show results from other wikis
885 *
886 * @param SearchResultSet|array $matches
887 * @param string $query
888 *
889 * @return string
890 */
891 protected function showInterwiki( $matches, $query ) {
892 global $wgContLang;
893
894 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
895 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
896 $out .= "<ul class='mw-search-iwresults'>\n";
897
898 // work out custom project captions
899 $this->getCustomCaptions();
900
901 if ( !is_array( $matches ) ) {
902 $matches = array( $matches );
903 }
904
905 foreach ( $matches as $set ) {
906 $prev = null;
907 $result = $set->next();
908 while ( $result ) {
909 $out .= $this->showInterwikiHit( $result, $prev, $query );
910 $prev = $result->getInterwikiPrefix();
911 $result = $set->next();
912 }
913 }
914
915 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
916 $out .= "</ul></div>\n";
917
918 // convert the whole thing to desired language variant
919 $out = $wgContLang->convert( $out );
920
921 return $out;
922 }
923
924 /**
925 * Show single interwiki link
926 *
927 * @param SearchResult $result
928 * @param string $lastInterwiki
929 * @param string $query
930 *
931 * @return string
932 */
933 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
934
935 if ( $result->isBrokenTitle() ) {
936 return '';
937 }
938
939 $title = $result->getTitle();
940
941 $titleSnippet = $result->getTitleSnippet();
942
943 if ( $titleSnippet == '' ) {
944 $titleSnippet = null;
945 }
946
947 $link = Linker::linkKnown(
948 $title,
949 $titleSnippet
950 );
951
952 // format redirect if any
953 $redirectTitle = $result->getRedirectTitle();
954 $redirectText = $result->getRedirectSnippet();
955 $redirect = '';
956 if ( !is_null( $redirectTitle ) ) {
957 if ( $redirectText == '' ) {
958 $redirectText = null;
959 }
960
961 $redirect = "<span class='searchalttitle'>" .
962 $this->msg( 'search-redirect' )->rawParams(
963 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
964 "</span>";
965 }
966
967 $out = "";
968 // display project name
969 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
970 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
971 // captions from 'search-interwiki-custom'
972 $caption = $this->customCaptions[$title->getInterwiki()];
973 } else {
974 // default is to show the hostname of the other wiki which might suck
975 // if there are many wikis on one hostname
976 $parsed = wfParseUrl( $title->getFullURL() );
977 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
978 }
979 // "more results" link (special page stuff could be localized, but we might not know target lang)
980 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
981 $searchLink = Linker::linkKnown(
982 $searchTitle,
983 $this->msg( 'search-interwiki-more' )->text(),
984 array(),
985 array(
986 'search' => $query,
987 'fulltext' => 'Search'
988 )
989 );
990 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
991 {$searchLink}</span>{$caption}</div>\n<ul>";
992 }
993
994 $out .= "<li>{$link} {$redirect}</li>\n";
995
996 return $out;
997 }
998
999 /**
1000 * Generates the power search box at [[Special:Search]]
1001 *
1002 * @param string $term Search term
1003 * @param array $opts
1004 * @return string HTML form
1005 */
1006 protected function powerSearchBox( $term, $opts ) {
1007 global $wgContLang;
1008
1009 // Groups namespaces into rows according to subject
1010 $rows = array();
1011 foreach ( SearchEngine::searchableNamespaces() as $namespace => $name ) {
1012 $subject = MWNamespace::getSubject( $namespace );
1013 if ( !array_key_exists( $subject, $rows ) ) {
1014 $rows[$subject] = "";
1015 }
1016
1017 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1018 if ( $name == '' ) {
1019 $name = $this->msg( 'blanknamespace' )->text();
1020 }
1021
1022 $rows[$subject] .=
1023 Xml::openElement( 'td' ) .
1024 Xml::checkLabel(
1025 $name,
1026 "ns{$namespace}",
1027 "mw-search-ns{$namespace}",
1028 in_array( $namespace, $this->namespaces )
1029 ) .
1030 Xml::closeElement( 'td' );
1031 }
1032
1033 $rows = array_values( $rows );
1034 $numRows = count( $rows );
1035
1036 // Lays out namespaces in multiple floating two-column tables so they'll
1037 // be arranged nicely while still accommodating different screen widths
1038 $namespaceTables = '';
1039 for ( $i = 0; $i < $numRows; $i += 4 ) {
1040 $namespaceTables .= Xml::openElement( 'table' );
1041
1042 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1043 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1044 }
1045
1046 $namespaceTables .= Xml::closeElement( 'table' );
1047 }
1048
1049 $showSections = array( 'namespaceTables' => $namespaceTables );
1050
1051 Hooks::run( 'SpecialSearchPowerBox', array( &$showSections, $term, $opts ) );
1052
1053 $hidden = '';
1054 foreach ( $opts as $key => $value ) {
1055 $hidden .= Html::hidden( $key, $value );
1056 }
1057
1058 # Stuff to feed saveNamespaces()
1059 $remember = '';
1060 $user = $this->getUser();
1061 if ( $user->isLoggedIn() ) {
1062 $remember .= Xml::checkLabel(
1063 $this->msg( 'powersearch-remember' )->text(),
1064 'nsRemember',
1065 'mw-search-powersearch-remember',
1066 false,
1067 // The token goes here rather than in a hidden field so it
1068 // is only sent when necessary (not every form submission).
1069 array( 'value' => $user->getEditToken(
1070 'searchnamespace',
1071 $this->getRequest()
1072 ) )
1073 );
1074 }
1075
1076 // Return final output
1077 return Xml::openElement( 'fieldset', array( 'id' => 'mw-searchoptions' ) ) .
1078 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1079 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1080 Xml::element( 'div', array( 'id' => 'mw-search-togglebox' ), '', false ) .
1081 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1082 implode( Xml::element( 'div', array( 'class' => 'divider' ), '', false ), $showSections ) .
1083 $hidden .
1084 Xml::element( 'div', array( 'class' => 'divider' ), '', false ) .
1085 $remember .
1086 Xml::closeElement( 'fieldset' );
1087 }
1088
1089 /**
1090 * @return array
1091 */
1092 protected function getSearchProfiles() {
1093 // Builds list of Search Types (profiles)
1094 $nsAllSet = array_keys( SearchEngine::searchableNamespaces() );
1095
1096 $profiles = array(
1097 'default' => array(
1098 'message' => 'searchprofile-articles',
1099 'tooltip' => 'searchprofile-articles-tooltip',
1100 'namespaces' => SearchEngine::defaultNamespaces(),
1101 'namespace-messages' => SearchEngine::namespacesAsText(
1102 SearchEngine::defaultNamespaces()
1103 ),
1104 ),
1105 'images' => array(
1106 'message' => 'searchprofile-images',
1107 'tooltip' => 'searchprofile-images-tooltip',
1108 'namespaces' => array( NS_FILE ),
1109 ),
1110 'all' => array(
1111 'message' => 'searchprofile-everything',
1112 'tooltip' => 'searchprofile-everything-tooltip',
1113 'namespaces' => $nsAllSet,
1114 ),
1115 'advanced' => array(
1116 'message' => 'searchprofile-advanced',
1117 'tooltip' => 'searchprofile-advanced-tooltip',
1118 'namespaces' => self::NAMESPACES_CURRENT,
1119 )
1120 );
1121
1122 Hooks::run( 'SpecialSearchProfiles', array( &$profiles ) );
1123
1124 foreach ( $profiles as &$data ) {
1125 if ( !is_array( $data['namespaces'] ) ) {
1126 continue;
1127 }
1128 sort( $data['namespaces'] );
1129 }
1130
1131 return $profiles;
1132 }
1133
1134 /**
1135 * @param string $term
1136 * @return string
1137 */
1138 protected function searchProfileTabs( $term ) {
1139 $out = Xml::openElement( 'div', array( 'class' => 'mw-search-profile-tabs' ) );
1140
1141 $bareterm = $term;
1142 if ( $this->startsWithImage( $term ) ) {
1143 // Deletes prefixes
1144 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1145 }
1146
1147 $profiles = $this->getSearchProfiles();
1148 $lang = $this->getLanguage();
1149
1150 // Outputs XML for Search Types
1151 $out .= Xml::openElement( 'div', array( 'class' => 'search-types' ) );
1152 $out .= Xml::openElement( 'ul' );
1153 foreach ( $profiles as $id => $profile ) {
1154 if ( !isset( $profile['parameters'] ) ) {
1155 $profile['parameters'] = array();
1156 }
1157 $profile['parameters']['profile'] = $id;
1158
1159 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1160 $lang->commaList( $profile['namespace-messages'] ) : null;
1161 $out .= Xml::tags(
1162 'li',
1163 array(
1164 'class' => $this->profile === $id ? 'current' : 'normal'
1165 ),
1166 $this->makeSearchLink(
1167 $bareterm,
1168 array(),
1169 $this->msg( $profile['message'] )->text(),
1170 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1171 $profile['parameters']
1172 )
1173 );
1174 }
1175 $out .= Xml::closeElement( 'ul' );
1176 $out .= Xml::closeElement( 'div' );
1177 $out .= Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1178 $out .= Xml::closeElement( 'div' );
1179
1180 return $out;
1181 }
1182
1183 /**
1184 * @param string $term Search term
1185 * @return string
1186 */
1187 protected function searchOptions( $term ) {
1188 $out = '';
1189 $opts = array();
1190 $opts['profile'] = $this->profile;
1191
1192 if ( $this->isPowerSearch() ) {
1193 $out .= $this->powerSearchBox( $term, $opts );
1194 } else {
1195 $form = '';
1196 Hooks::run( 'SpecialSearchProfileForm', array( $this, &$form, $this->profile, $term, $opts ) );
1197 $out .= $form;
1198 }
1199
1200 return $out;
1201 }
1202
1203 /**
1204 * @param string $term
1205 * @param int $resultsShown
1206 * @param int $totalNum
1207 * @return string
1208 */
1209 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1210 $out = Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() );
1211 $out .= Html::hidden( 'profile', $this->profile ) . "\n";
1212 // Term box
1213 $out .= Html::input( 'search', $term, 'search', array(
1214 'id' => $this->isPowerSearch() ? 'powerSearchText' : 'searchText',
1215 'size' => '50',
1216 'autofocus' => trim( $term ) === '',
1217 'class' => 'mw-ui-input mw-ui-input-inline',
1218 ) ) . "\n";
1219 $out .= Html::hidden( 'fulltext', 'Search' ) . "\n";
1220 $out .= Html::submitButton(
1221 $this->msg( 'searchbutton' )->text(),
1222 array( 'class' => 'mw-ui-button mw-ui-progressive' ),
1223 array( 'mw-ui-progressive' )
1224 ) . "\n";
1225
1226 // Results-info
1227 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1228 $top = $this->msg( 'search-showingresults' )
1229 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1230 ->numParams( $resultsShown )
1231 ->parse();
1232 $out .= Xml::tags( 'div', array( 'class' => 'results-info' ), $top ) .
1233 Xml::element( 'div', array( 'style' => 'clear:both' ), '', false );
1234 }
1235
1236 return $out;
1237 }
1238
1239 /**
1240 * Make a search link with some target namespaces
1241 *
1242 * @param string $term
1243 * @param array $namespaces Ignored
1244 * @param string $label Link's text
1245 * @param string $tooltip Link's tooltip
1246 * @param array $params Query string parameters
1247 * @return string HTML fragment
1248 */
1249 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = array() ) {
1250 $opt = $params;
1251 foreach ( $namespaces as $n ) {
1252 $opt['ns' . $n] = 1;
1253 }
1254
1255 $stParams = array_merge(
1256 array(
1257 'search' => $term,
1258 'fulltext' => $this->msg( 'search' )->text()
1259 ),
1260 $opt
1261 );
1262
1263 return Xml::element(
1264 'a',
1265 array(
1266 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1267 'title' => $tooltip
1268 ),
1269 $label
1270 );
1271 }
1272
1273 /**
1274 * Check if query starts with image: prefix
1275 *
1276 * @param string $term The string to check
1277 * @return bool
1278 */
1279 protected function startsWithImage( $term ) {
1280 global $wgContLang;
1281
1282 $parts = explode( ':', $term );
1283 if ( count( $parts ) > 1 ) {
1284 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1285 }
1286
1287 return false;
1288 }
1289
1290 /**
1291 * Check if query starts with all: prefix
1292 *
1293 * @param string $term The string to check
1294 * @return bool
1295 */
1296 protected function startsWithAll( $term ) {
1297
1298 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1299
1300 $parts = explode( ':', $term );
1301 if ( count( $parts ) > 1 ) {
1302 return $parts[0] == $allkeyword;
1303 }
1304
1305 return false;
1306 }
1307
1308 /**
1309 * @since 1.18
1310 *
1311 * @return SearchEngine
1312 */
1313 public function getSearchEngine() {
1314 if ( $this->searchEngine === null ) {
1315 $this->searchEngine = $this->searchEngineType ?
1316 SearchEngine::create( $this->searchEngineType ) : SearchEngine::create();
1317 }
1318
1319 return $this->searchEngine;
1320 }
1321
1322 /**
1323 * Current search profile.
1324 * @return null|string
1325 */
1326 function getProfile() {
1327 return $this->profile;
1328 }
1329
1330 /**
1331 * Current namespaces.
1332 * @return array
1333 */
1334 function getNamespaces() {
1335 return $this->namespaces;
1336 }
1337
1338 /**
1339 * Users of hook SpecialSearchSetupEngine can use this to
1340 * add more params to links to not lose selection when
1341 * user navigates search results.
1342 * @since 1.18
1343 *
1344 * @param string $key
1345 * @param mixed $value
1346 */
1347 public function setExtraParam( $key, $value ) {
1348 $this->extraParams[$key] = $value;
1349 }
1350
1351 protected function getGroupName() {
1352 return 'pages';
1353 }
1354 }