Extract search form from SpecialSearch into widget
[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 $out = $this->getOutput();
105
106 // Fetch the search term
107 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
108
109 // Historically search terms have been accepted not only in the search query
110 // parameter, but also as part of the primary url. This can have PII implications
111 // in releasing page view data. As such issue a 301 redirect to the correct
112 // URL.
113 if ( strlen( $par ) && !strlen( $term ) ) {
114 $query = $request->getValues();
115 unset( $query['title'] );
116 // Strip underscores from title parameter; most of the time we'll want
117 // text form here. But don't strip underscores from actual text params!
118 $query['search'] = str_replace( '_', ' ', $par );
119 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
120 return;
121 }
122
123 // Need to load selected namespaces before handling nsRemember
124 $this->load();
125 // TODO: This performs database actions on GET request, which is going to
126 // be a problem for our multi-datacenter work.
127 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
128 $this->saveNamespaces();
129 // Remove the token from the URL to prevent the user from inadvertently
130 // exposing it (e.g. by pasting it into a public wiki page) or undoing
131 // later settings changes (e.g. by reloading the page).
132 $query = $request->getValues();
133 unset( $query['title'], $query['nsRemember'] );
134 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
135 return;
136 }
137
138 $this->searchEngineType = $request->getVal( 'srbackend' );
139 if (
140 !$request->getVal( 'fulltext' ) &&
141 $request->getVal( 'offset' ) === null
142 ) {
143 $url = $this->goResult( $term );
144 if ( $url !== null ) {
145 // successful 'go'
146 $out->redirect( $url );
147 return;
148 }
149 }
150
151 $this->setupPage( $term );
152
153 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
154 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
155 if ( $searchForwardUrl ) {
156 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
157 $out->redirect( $url );
158 } else {
159 $out->addHTML(
160 "<fieldset>" .
161 "<legend>" .
162 $this->msg( 'search-external' )->escaped() .
163 "</legend>" .
164 "<p class='mw-searchdisabled'>" .
165 $this->msg( 'searchdisabled' )->escaped() .
166 "</p>" .
167 $this->msg( 'googlesearch' )->rawParams(
168 htmlspecialchars( $term ),
169 'UTF-8',
170 $this->msg( 'searchbutton' )->escaped()
171 )->text() .
172 "</fieldset>"
173 );
174 }
175
176 return;
177 }
178
179 $this->showResults( $term );
180 }
181
182 /**
183 * Set up basic search parameters from the request and user settings.
184 *
185 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
186 */
187 public function load() {
188 $request = $this->getRequest();
189 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
190 $this->mPrefix = $request->getVal( 'prefix', '' );
191
192 $user = $this->getUser();
193
194 # Extract manually requested namespaces
195 $nslist = $this->powerSearch( $request );
196 if ( !count( $nslist ) ) {
197 # Fallback to user preference
198 $nslist = $this->searchConfig->userNamespaces( $user );
199 }
200
201 $profile = null;
202 if ( !count( $nslist ) ) {
203 $profile = 'default';
204 }
205
206 $profile = $request->getVal( 'profile', $profile );
207 $profiles = $this->getSearchProfiles();
208 if ( $profile === null ) {
209 // BC with old request format
210 $profile = 'advanced';
211 foreach ( $profiles as $key => $data ) {
212 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
213 $profile = $key;
214 }
215 }
216 $this->namespaces = $nslist;
217 } elseif ( $profile === 'advanced' ) {
218 $this->namespaces = $nslist;
219 } else {
220 if ( isset( $profiles[$profile]['namespaces'] ) ) {
221 $this->namespaces = $profiles[$profile]['namespaces'];
222 } else {
223 // Unknown profile requested
224 $profile = 'default';
225 $this->namespaces = $profiles['default']['namespaces'];
226 }
227 }
228
229 $this->fulltext = $request->getVal( 'fulltext' );
230 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
231 $this->profile = $profile;
232 }
233
234 /**
235 * If an exact title match can be found, jump straight ahead to it.
236 *
237 * @param string $term
238 * @return string|null The url to redirect to, or null if no redirect.
239 */
240 public function goResult( $term ) {
241 # If the string cannot be used to create a title
242 if ( is_null( Title::newFromText( $term ) ) ) {
243 return null;
244 }
245 # If there's an exact or very near match, jump right there.
246 $title = $this->getSearchEngine()
247 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
248 if ( is_null( $title ) ) {
249 return null;
250 }
251 $url = null;
252 if ( !Hooks::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
253 return null;
254 }
255
256 return $url === null ? $title->getFullURL() : $url;
257 }
258
259 /**
260 * @param string $term
261 */
262 public function showResults( $term ) {
263 global $wgContLang;
264
265 if ( $this->searchEngineType !== null ) {
266 $this->setExtraParam( 'srbackend', $this->searchEngineType );
267 }
268
269 $out = $this->getOutput();
270 $formWidget = new MediaWiki\Widget\Search\SearchFormWidget(
271 $this,
272 $this->searchConfig,
273 $this->getSearchProfiles()
274 );
275 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
276 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
277 // Empty query -- straight view of search form
278 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
279 # Hook requested termination
280 return;
281 }
282 $out->enableOOUI();
283 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
284 // only do the form render here for the empty $term case. Rendering
285 // the form when a search is provided is repeated below.
286 $out->addHTML( $formWidget->render(
287 $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch()
288 ) );
289 return;
290 }
291
292 $search = $this->getSearchEngine();
293 $search->setFeatureData( 'rewrite', $this->runSuggestion );
294 $search->setLimitOffset( $this->limit, $this->offset );
295 $search->setNamespaces( $this->namespaces );
296 $search->prefix = $this->mPrefix;
297 $term = $search->transformSearchTerm( $term );
298
299 Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
300 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
301 # Hook requested termination
302 return;
303 }
304
305 $title = Title::newFromText( $term );
306 $showSuggestion = $title === null || !$title->isKnown();
307 $search->setShowSuggestion( $showSuggestion );
308
309 // fetch search results
310 $rewritten = $search->replacePrefixes( $term );
311
312 $titleMatches = $search->searchTitle( $rewritten );
313 $textMatches = $search->searchText( $rewritten );
314
315 $textStatus = null;
316 if ( $textMatches instanceof Status ) {
317 $textStatus = $textMatches;
318 $textMatches = $textStatus->getValue();
319 }
320
321 // Get number of results
322 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
323 if ( $titleMatches ) {
324 $titleMatchesNum = $titleMatches->numRows();
325 $numTitleMatches = $titleMatches->getTotalHits();
326 }
327 if ( $textMatches ) {
328 $textMatchesNum = $textMatches->numRows();
329 $numTextMatches = $textMatches->getTotalHits();
330 }
331 $num = $titleMatchesNum + $textMatchesNum;
332 $totalRes = $numTitleMatches + $numTextMatches;
333
334 // start rendering the page
335 $out->enableOOUI();
336 $out->addHTML( $formWidget->render(
337 $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch()
338 ) );
339
340 // did you mean... suggestions
341 if ( $textMatches ) {
342 if ( $textMatches->hasRewrittenQuery() ) {
343 $out->addHTML( $this->getDidYouMeanRewrittenHtml( $term, $textMatches ) );
344 } elseif ( $textMatches->hasSuggestion() ) {
345 $out->addHTML( $this->getDidYouMeanHtml( $textMatches ) );
346 }
347 }
348
349 $out->addHTML( "<div class='searchresults'>" );
350
351 $hasErrors = $textStatus && $textStatus->getErrors();
352 $hasOtherResults = $textMatches &&
353 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
354
355 if ( $hasErrors ) {
356 list( $error, $warning ) = $textStatus->splitByErrorType();
357 if ( $error->getErrors() ) {
358 $out->addHTML( Html::rawElement(
359 'div',
360 [ 'class' => 'errorbox' ],
361 $error->getHTML( 'search-error' )
362 ) );
363 }
364 if ( $warning->getErrors() ) {
365 $out->addHTML( Html::rawElement(
366 'div',
367 [ 'class' => 'warningbox' ],
368 $warning->getHTML( 'search-warning' )
369 ) );
370 }
371 }
372
373 // Show the create link ahead
374 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
375
376 // If we have no results and have not already displayed an error message
377 if ( $num === 0 && !$hasErrors ) {
378 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
379 $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
380 wfEscapeWikiText( $term )
381 ] );
382 }
383
384 Hooks::run( 'SpecialSearchResults', [ $term, $titleMatches, $textMatches ] );
385
386 $out->parserOptions()->setEditSection( false );
387 if ( $titleMatches ) {
388 if ( $numTitleMatches > 0 ) {
389 $out->wrapWikiMsg( "==$1==\n", 'titlematches' );
390 $out->addHTML( $this->showMatches( $titleMatches ) );
391 }
392 $titleMatches->free();
393 }
394
395 if ( $textMatches ) {
396 // output appropriate heading
397 if ( $numTextMatches > 0 && $numTitleMatches > 0 ) {
398 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
399 // if no title matches the heading is redundant
400 $out->wrapWikiMsg( "==$1==\n", 'textmatches' );
401 }
402
403 // show results
404 if ( $numTextMatches > 0 ) {
405 $search->augmentSearchResults( $textMatches );
406 $out->addHTML( $this->showMatches( $textMatches ) );
407 }
408
409 // show secondary interwiki results if any
410 if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
411 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
412 SearchResultSet::SECONDARY_RESULTS ), $term ) );
413 }
414 }
415
416 if ( $hasOtherResults ) {
417 foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
418 as $interwiki => $interwikiResult ) {
419 if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
420 // ignore bad interwikis for now
421 continue;
422 }
423 // TODO: wiki header
424 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
425 }
426 }
427
428 if ( $textMatches ) {
429 $textMatches->free();
430 }
431
432 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
433
434 // prev/next links
435 if ( $totalRes > $this->limit || $this->offset ) {
436 $prevnext = $this->getLanguage()->viewPrevNext(
437 $this->getPageTitle(),
438 $this->offset,
439 $this->limit,
440 $this->powerSearchOptions() + [ 'search' => $term ],
441 $this->limit + $this->offset >= $totalRes
442 );
443 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
444 }
445
446 // Close <div class='searchresults'>
447 $out->addHTML( "</div>" );
448
449 Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
450 }
451
452 /**
453 * Produce wiki header for interwiki results
454 * @param string $interwiki Interwiki name
455 * @param SearchResultSet $interwikiResult The result set
456 * @return string
457 */
458 protected function interwikiHeader( $interwiki, $interwikiResult ) {
459 // TODO: we need to figure out how to name wikis correctly
460 $wikiMsg = $this->msg( 'search-interwiki-results-' . $interwiki )->parse();
461 return "<p class=\"mw-search-interwiki-header mw-search-visualclear\">\n$wikiMsg</p>";
462 }
463
464 /**
465 * Generates HTML shown to the user when we have a suggestion about a query
466 * that might give more results than their current query.
467 */
468 protected function getDidYouMeanHtml( SearchResultSet $textMatches ) {
469 # mirror Go/Search behavior of original request ..
470 $params = [ 'search' => $textMatches->getSuggestionQuery() ];
471 if ( $this->fulltext === null ) {
472 $params['fulltext'] = 'Search';
473 } else {
474 $params['fulltext'] = $this->fulltext;
475 }
476 $stParams = array_merge( $params, $this->powerSearchOptions() );
477
478 $linkRenderer = $this->getLinkRenderer();
479
480 $snippet = $textMatches->getSuggestionSnippet() ?: null;
481 if ( $snippet !== null ) {
482 $snippet = new HtmlArmor( $snippet );
483 }
484
485 $suggest = $linkRenderer->makeKnownLink(
486 $this->getPageTitle(),
487 $snippet,
488 [ 'id' => 'mw-search-DYM-suggestion' ],
489 $stParams
490 );
491
492 # HTML of did you mean... search suggestion link
493 return Html::rawElement(
494 'div',
495 [ 'class' => 'searchdidyoumean' ],
496 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
497 );
498 }
499
500 /**
501 * Generates HTML shown to user when their query has been internally rewritten,
502 * and the results of the rewritten query are being returned.
503 *
504 * @param string $term The users search input
505 * @param SearchResultSet $textMatches The response to the users initial search request
506 * @return string HTML linking the user to their original $term query, and the one
507 * suggested by $textMatches.
508 */
509 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
510 // Showing results for '$rewritten'
511 // Search instead for '$orig'
512
513 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
514 if ( $this->fulltext === null ) {
515 $params['fulltext'] = 'Search';
516 } else {
517 $params['fulltext'] = $this->fulltext;
518 }
519 $stParams = array_merge( $params, $this->powerSearchOptions() );
520
521 $linkRenderer = $this->getLinkRenderer();
522
523 $snippet = $textMatches->getQueryAfterRewriteSnippet() ?: null;
524 if ( $snippet !== null ) {
525 $snippet = new HtmlArmor( $snippet );
526 }
527
528 $rewritten = $linkRenderer->makeKnownLink(
529 $this->getPageTitle(),
530 $snippet,
531 [ 'id' => 'mw-search-DYM-rewritten' ],
532 $stParams
533 );
534
535 $stParams['search'] = $term;
536 $stParams['runsuggestion'] = 0;
537 $original = $linkRenderer->makeKnownLink(
538 $this->getPageTitle(),
539 $term,
540 [ 'id' => 'mw-search-DYM-original' ],
541 $stParams
542 );
543
544 return Html::rawElement(
545 'div',
546 [ 'class' => 'searchdidyoumean' ],
547 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
548 );
549 }
550
551 /**
552 * @param Title $title
553 * @param int $num The number of search results found
554 * @param null|SearchResultSet $titleMatches Results from title search
555 * @param null|SearchResultSet $textMatches Results from text search
556 */
557 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
558 // show direct page/create link if applicable
559
560 // Check DBkey !== '' in case of fragment link only.
561 if ( is_null( $title ) || $title->getDBkey() === ''
562 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
563 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
564 ) {
565 // invalid title
566 // preserve the paragraph for margins etc...
567 $this->getOutput()->addHTML( '<p></p>' );
568
569 return;
570 }
571
572 $messageName = 'searchmenu-new-nocreate';
573 $linkClass = 'mw-search-createlink';
574
575 if ( !$title->isExternal() ) {
576 if ( $title->isKnown() ) {
577 $messageName = 'searchmenu-exists';
578 $linkClass = 'mw-search-exists';
579 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
580 $messageName = 'searchmenu-new';
581 }
582 }
583
584 $params = [
585 $messageName,
586 wfEscapeWikiText( $title->getPrefixedText() ),
587 Message::numParam( $num )
588 ];
589 Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
590
591 // Extensions using the hook might still return an empty $messageName
592 if ( $messageName ) {
593 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
594 } else {
595 // preserve the paragraph for margins etc...
596 $this->getOutput()->addHTML( '<p></p>' );
597 }
598 }
599
600 /**
601 * Sets up everything for the HTML output page including styles, javascript,
602 * page title, etc.
603 *
604 * @param string $term
605 */
606 protected function setupPage( $term ) {
607 $out = $this->getOutput();
608
609 $this->setHeaders();
610 $this->outputHeader();
611 // TODO: Is this true? The namespace remember uses a user token
612 // on save.
613 $out->allowClickjacking();
614 $this->addHelpLink( 'Help:Searching' );
615
616 if ( strval( $term ) !== '' ) {
617 $out->setPageTitle( $this->msg( 'searchresults' ) );
618 $out->setHTMLTitle( $this->msg( 'pagetitle' )
619 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
620 ->inContentLanguage()->text()
621 );
622 }
623
624 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
625 $out->addModules( 'mediawiki.special.search' );
626 $out->addModuleStyles( [
627 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
628 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
629 ] );
630 }
631
632 /**
633 * Return true if current search is a power (advanced) search
634 *
635 * @return bool
636 */
637 protected function isPowerSearch() {
638 return $this->profile === 'advanced';
639 }
640
641 /**
642 * Extract "power search" namespace settings from the request object,
643 * returning a list of index numbers to search.
644 *
645 * @param WebRequest $request
646 * @return array
647 */
648 protected function powerSearch( &$request ) {
649 $arr = [];
650 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
651 if ( $request->getCheck( 'ns' . $ns ) ) {
652 $arr[] = $ns;
653 }
654 }
655
656 return $arr;
657 }
658
659 /**
660 * Reconstruct the 'power search' options for links
661 *
662 * @return array
663 */
664 protected function powerSearchOptions() {
665 $opt = [];
666 if ( $this->isPowerSearch() ) {
667 foreach ( $this->namespaces as $n ) {
668 $opt['ns' . $n] = 1;
669 }
670 } else {
671 $opt['profile'] = $this->profile;
672 }
673
674 return $opt + $this->extraParams;
675 }
676
677 /**
678 * Save namespace preferences when we're supposed to
679 *
680 * @return bool Whether we wrote something
681 */
682 protected function saveNamespaces() {
683 $user = $this->getUser();
684 $request = $this->getRequest();
685
686 if ( $user->isLoggedIn() &&
687 $user->matchEditToken(
688 $request->getVal( 'nsRemember' ),
689 'searchnamespace',
690 $request
691 ) && !wfReadOnly()
692 ) {
693 // Reset namespace preferences: namespaces are not searched
694 // when they're not mentioned in the URL parameters.
695 foreach ( MWNamespace::getValidNamespaces() as $n ) {
696 $user->setOption( 'searchNs' . $n, false );
697 }
698 // The request parameters include all the namespaces to be searched.
699 // Even if they're the same as an existing profile, they're not eaten.
700 foreach ( $this->namespaces as $n ) {
701 $user->setOption( 'searchNs' . $n, true );
702 }
703
704 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
705 $user->saveSettings();
706 } );
707
708 return true;
709 }
710
711 return false;
712 }
713
714 /**
715 * Show whole set of results
716 *
717 * @param SearchResultSet $matches
718 * @param string $interwiki Interwiki name
719 *
720 * @return string
721 */
722 protected function showMatches( $matches, $interwiki = null ) {
723 global $wgContLang;
724
725 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
726 $out = '';
727 $result = $matches->next();
728 $pos = $this->offset;
729
730 if ( $result && $interwiki ) {
731 $out .= $this->interwikiHeader( $interwiki, $matches );
732 }
733
734 $out .= "<ul class='mw-search-results'>\n";
735 $widget = new \MediaWiki\Widget\Search\FullSearchResultWidget(
736 $this,
737 $this->getLinkRenderer()
738 );
739 while ( $result ) {
740 $out .= $widget->render( $result, $terms, $pos++ );
741 $result = $matches->next();
742 }
743 $out .= "</ul>\n";
744
745 // convert the whole thing to desired language variant
746 $out = $wgContLang->convert( $out );
747
748 return $out;
749 }
750
751 /**
752 * Extract custom captions from search-interwiki-custom message
753 */
754 protected function getCustomCaptions() {
755 if ( is_null( $this->customCaptions ) ) {
756 $this->customCaptions = [];
757 // format per line <iwprefix>:<caption>
758 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
759 foreach ( $customLines as $line ) {
760 $parts = explode( ":", $line, 2 );
761 if ( count( $parts ) == 2 ) { // validate line
762 $this->customCaptions[$parts[0]] = $parts[1];
763 }
764 }
765 }
766 }
767
768 /**
769 * Show results from other wikis
770 *
771 * @param SearchResultSet|array $matches
772 * @param string $terms
773 *
774 * @return string
775 */
776 protected function showInterwiki( $matches, $terms ) {
777 global $wgContLang;
778
779 // work out custom project captions
780 $this->getCustomCaptions();
781
782 if ( !is_array( $matches ) ) {
783 $matches = [ $matches ];
784 }
785
786 $iwResults = [];
787 foreach ( $matches as $set ) {
788 $result = $set->next();
789 while ( $result ) {
790 if ( !$result->isBrokenTitle() ) {
791 $iwResults[$result->getTitle()->getInterwiki()][] = $result;
792 }
793 $result = $set->next();
794 }
795 }
796
797 $out = '';
798 $widget = new MediaWiki\Widget\Search\SimpleSearchResultWidget(
799 $this,
800 $this->getLinkRenderer()
801 );
802 foreach ( $iwResults as $iwPrefix => $results ) {
803 $out .= $this->iwHeaderHtml( $iwPrefix, $terms );
804 $out .= "<ul class='mw-search-iwresults'>";
805 foreach ( $results as $result ) {
806 // This makes the bold asumption interwiki results are never paginated.
807 // That's currently true, but could change at some point?
808 $out .= $widget->render( $result, $terms, 0 );
809 }
810 $out .= "</ul>";
811 }
812
813 $out =
814 "<div id='mw-search-interwiki'>" .
815 "<div id='mw-search-interwiki-caption'>" .
816 $this->msg( 'search-interwiki-caption' )->escaped() .
817 "</div>" .
818 $out .
819 "</div>";
820
821 // convert the whole thing to desired language variant
822 return $wgContLang->convert( $out );
823 }
824
825 /**
826 * @param string $iwPrefix The interwiki prefix to render a header for
827 * @param string $terms The user-provided search terms
828 */
829 protected function iwHeaderHtml( $iwPrefix, $terms ) {
830 if ( isset( $this->customCaptions[$iwPrefix] ) ) {
831 $caption = $this->customCaptions[$iwPrefix];
832 } else {
833 $iwLookup = MediaWiki\MediaWikiServices::getInstance()->getInterwikiLookup();
834 $interwiki = $iwLookup->fetch( $iwPrefix );
835 $parsed = wfParseUrl( wfExpandUrl( $interwiki ? $interwiki->getURL() : '/' ) );
836 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
837 }
838 $searchLink = Linker::linkKnown(
839 Title::newFromText( "$iwPrefix:Special:Search" ),
840 $this->msg( 'search-interwiki-more' )->text(),
841 [],
842 [
843 'search' => $terms,
844 'fulltext' => 1,
845 ]
846 );
847 return
848 "<div class='mw-search-interwiki-project'>" .
849 "<span class='mw-search-interwiki-more'>{$searchLink}</span>" .
850 $caption .
851 "</div>";
852 }
853
854 /**
855 * @return array
856 */
857 protected function getSearchProfiles() {
858 // Builds list of Search Types (profiles)
859 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
860 $defaultNs = $this->searchConfig->defaultNamespaces();
861 $profiles = [
862 'default' => [
863 'message' => 'searchprofile-articles',
864 'tooltip' => 'searchprofile-articles-tooltip',
865 'namespaces' => $defaultNs,
866 'namespace-messages' => $this->searchConfig->namespacesAsText(
867 $defaultNs
868 ),
869 ],
870 'images' => [
871 'message' => 'searchprofile-images',
872 'tooltip' => 'searchprofile-images-tooltip',
873 'namespaces' => [ NS_FILE ],
874 ],
875 'all' => [
876 'message' => 'searchprofile-everything',
877 'tooltip' => 'searchprofile-everything-tooltip',
878 'namespaces' => $nsAllSet,
879 ],
880 'advanced' => [
881 'message' => 'searchprofile-advanced',
882 'tooltip' => 'searchprofile-advanced-tooltip',
883 'namespaces' => self::NAMESPACES_CURRENT,
884 ]
885 ];
886
887 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
888
889 foreach ( $profiles as &$data ) {
890 if ( !is_array( $data['namespaces'] ) ) {
891 continue;
892 }
893 sort( $data['namespaces'] );
894 }
895
896 return $profiles;
897 }
898
899 /**
900 * @since 1.18
901 *
902 * @return SearchEngine
903 */
904 public function getSearchEngine() {
905 if ( $this->searchEngine === null ) {
906 $this->searchEngine = $this->searchEngineType ?
907 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
908 MediaWikiServices::getInstance()->newSearchEngine();
909 }
910
911 return $this->searchEngine;
912 }
913
914 /**
915 * Current search profile.
916 * @return null|string
917 */
918 function getProfile() {
919 return $this->profile;
920 }
921
922 /**
923 * Current namespaces.
924 * @return array
925 */
926 function getNamespaces() {
927 return $this->namespaces;
928 }
929
930 /**
931 * Users of hook SpecialSearchSetupEngine can use this to
932 * add more params to links to not lose selection when
933 * user navigates search results.
934 * @since 1.18
935 *
936 * @param string $key
937 * @param mixed $value
938 */
939 public function setExtraParam( $key, $value ) {
940 $this->extraParams[$key] = $value;
941 }
942
943 protected function getGroupName() {
944 return 'pages';
945 }
946 }