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