Cleanup execution flow through SpecialSearch::execute()
[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 $search = $this->getSearchEngine();
270 $search->setFeatureData( 'rewrite', $this->runSuggestion );
271 $search->setLimitOffset( $this->limit, $this->offset );
272 $search->setNamespaces( $this->namespaces );
273 $search->prefix = $this->mPrefix;
274 $term = $search->transformSearchTerm( $term );
275 $out = $this->getOutput();
276
277 Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
278 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
279 # Hook requested termination
280 return;
281 }
282
283 $title = Title::newFromText( $term );
284 $showSuggestion = $title === null || !$title->isKnown();
285 $search->setShowSuggestion( $showSuggestion );
286
287 // fetch search results
288 $rewritten = $search->replacePrefixes( $term );
289
290 $titleMatches = $search->searchTitle( $rewritten );
291 $textMatches = $search->searchText( $rewritten );
292
293 $textStatus = null;
294 if ( $textMatches instanceof Status ) {
295 $textStatus = $textMatches;
296 $textMatches = $textStatus->getValue();
297 }
298
299 // Get number of results
300 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
301 if ( $titleMatches ) {
302 $titleMatchesNum = $titleMatches->numRows();
303 $numTitleMatches = $titleMatches->getTotalHits();
304 }
305 if ( $textMatches ) {
306 $textMatchesNum = $textMatches->numRows();
307 $numTextMatches = $textMatches->getTotalHits();
308 }
309 $num = $titleMatchesNum + $textMatchesNum;
310 $totalRes = $numTitleMatches + $numTextMatches;
311
312 // start rendering the page
313 $out->enableOOUI();
314 $out->addHTML(
315 Xml::openElement(
316 'form',
317 [
318 'id' => ( $this->isPowerSearch() ? 'powersearch' : 'search' ),
319 'method' => 'get',
320 'action' => wfScript(),
321 ]
322 ) .
323 # This is an awful awful ID name. It's not a table, but we
324 # named it poorly from when this was a table so now we're
325 # stuck with it
326 "<div id='mw-search-top-table'>" .
327 $this->shortDialog( $term, $num, $totalRes ) .
328 "</div>" .
329 $this->searchProfileTabs( $term ) .
330 $this->searchOptions( $term ) .
331 '</form>'
332 );
333
334 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
335 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
336 // Empty query -- straight view of search form
337 return;
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 * Generates the power search box at [[Special:Search]]
856 *
857 * @param string $term Search term
858 * @param array $opts
859 * @return string HTML form
860 */
861 protected function powerSearchBox( $term, $opts ) {
862 global $wgContLang;
863
864 // Groups namespaces into rows according to subject
865 $rows = [];
866 foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
867 $subject = MWNamespace::getSubject( $namespace );
868 if ( !array_key_exists( $subject, $rows ) ) {
869 $rows[$subject] = "";
870 }
871
872 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
873 if ( $name == '' ) {
874 $name = $this->msg( 'blanknamespace' )->text();
875 }
876
877 $rows[$subject] .=
878 Xml::openElement( 'td' ) .
879 Xml::checkLabel(
880 $name,
881 "ns{$namespace}",
882 "mw-search-ns{$namespace}",
883 in_array( $namespace, $this->namespaces )
884 ) .
885 Xml::closeElement( 'td' );
886 }
887
888 $rows = array_values( $rows );
889 $numRows = count( $rows );
890
891 // Lays out namespaces in multiple floating two-column tables so they'll
892 // be arranged nicely while still accommodating different screen widths
893 $namespaceTables = '';
894 for ( $i = 0; $i < $numRows; $i += 4 ) {
895 $namespaceTables .= Xml::openElement( 'table' );
896
897 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
898 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
899 }
900
901 $namespaceTables .= Xml::closeElement( 'table' );
902 }
903
904 $showSections = [ 'namespaceTables' => $namespaceTables ];
905
906 Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
907
908 $hidden = '';
909 foreach ( $opts as $key => $value ) {
910 $hidden .= Html::hidden( $key, $value );
911 }
912
913 # Stuff to feed saveNamespaces()
914 $remember = '';
915 $user = $this->getUser();
916 if ( $user->isLoggedIn() ) {
917 $remember .= Xml::checkLabel(
918 $this->msg( 'powersearch-remember' )->text(),
919 'nsRemember',
920 'mw-search-powersearch-remember',
921 false,
922 // The token goes here rather than in a hidden field so it
923 // is only sent when necessary (not every form submission).
924 [ 'value' => $user->getEditToken(
925 'searchnamespace',
926 $this->getRequest()
927 ) ]
928 );
929 }
930
931 // Return final output
932 return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
933 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
934 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
935 Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
936 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
937 implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
938 $hidden .
939 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
940 $remember .
941 Xml::closeElement( 'fieldset' );
942 }
943
944 /**
945 * @return array
946 */
947 protected function getSearchProfiles() {
948 // Builds list of Search Types (profiles)
949 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
950 $defaultNs = $this->searchConfig->defaultNamespaces();
951 $profiles = [
952 'default' => [
953 'message' => 'searchprofile-articles',
954 'tooltip' => 'searchprofile-articles-tooltip',
955 'namespaces' => $defaultNs,
956 'namespace-messages' => $this->searchConfig->namespacesAsText(
957 $defaultNs
958 ),
959 ],
960 'images' => [
961 'message' => 'searchprofile-images',
962 'tooltip' => 'searchprofile-images-tooltip',
963 'namespaces' => [ NS_FILE ],
964 ],
965 'all' => [
966 'message' => 'searchprofile-everything',
967 'tooltip' => 'searchprofile-everything-tooltip',
968 'namespaces' => $nsAllSet,
969 ],
970 'advanced' => [
971 'message' => 'searchprofile-advanced',
972 'tooltip' => 'searchprofile-advanced-tooltip',
973 'namespaces' => self::NAMESPACES_CURRENT,
974 ]
975 ];
976
977 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
978
979 foreach ( $profiles as &$data ) {
980 if ( !is_array( $data['namespaces'] ) ) {
981 continue;
982 }
983 sort( $data['namespaces'] );
984 }
985
986 return $profiles;
987 }
988
989 /**
990 * @param string $term
991 * @return string
992 */
993 protected function searchProfileTabs( $term ) {
994 $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
995 Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
996
997 $bareterm = $term;
998 if ( $this->startsWithImage( $term ) ) {
999 // Deletes prefixes
1000 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1001 }
1002
1003 $profiles = $this->getSearchProfiles();
1004 $lang = $this->getLanguage();
1005
1006 // Outputs XML for Search Types
1007 $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1008 $out .= Xml::openElement( 'ul' );
1009 foreach ( $profiles as $id => $profile ) {
1010 if ( !isset( $profile['parameters'] ) ) {
1011 $profile['parameters'] = [];
1012 }
1013 $profile['parameters']['profile'] = $id;
1014
1015 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1016 $lang->commaList( $profile['namespace-messages'] ) : null;
1017 $out .= Xml::tags(
1018 'li',
1019 [
1020 'class' => $this->profile === $id ? 'current' : 'normal'
1021 ],
1022 $this->makeSearchLink(
1023 $bareterm,
1024 [],
1025 $this->msg( $profile['message'] )->text(),
1026 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1027 $profile['parameters']
1028 )
1029 );
1030 }
1031 $out .= Xml::closeElement( 'ul' );
1032 $out .= Xml::closeElement( 'div' );
1033 $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1034 $out .= Xml::closeElement( 'div' );
1035
1036 return $out;
1037 }
1038
1039 /**
1040 * @param string $term Search term
1041 * @return string
1042 */
1043 protected function searchOptions( $term ) {
1044 $out = '';
1045 $opts = [];
1046 $opts['profile'] = $this->profile;
1047
1048 if ( $this->isPowerSearch() ) {
1049 $out .= $this->powerSearchBox( $term, $opts );
1050 } else {
1051 $form = '';
1052 Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1053 $out .= $form;
1054 }
1055
1056 return $out;
1057 }
1058
1059 /**
1060 * @param string $term
1061 * @param int $resultsShown
1062 * @param int $totalNum
1063 * @return string
1064 */
1065 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1066 $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1067 'id' => 'searchText',
1068 'name' => 'search',
1069 'autofocus' => trim( $term ) === '',
1070 'value' => $term,
1071 'dataLocation' => 'content',
1072 'infusable' => true,
1073 ] );
1074
1075 $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1076 'type' => 'submit',
1077 'label' => $this->msg( 'searchbutton' )->text(),
1078 'flags' => [ 'progressive', 'primary' ],
1079 ] ), [
1080 'align' => 'top',
1081 ] );
1082
1083 $out =
1084 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1085 Html::hidden( 'profile', $this->profile ) .
1086 Html::hidden( 'fulltext', 'Search' ) .
1087 $layout;
1088
1089 // Results-info
1090 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1091 $top = $this->msg( 'search-showingresults' )
1092 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1093 ->numParams( $resultsShown )
1094 ->parse();
1095 $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1096 }
1097
1098 return $out;
1099 }
1100
1101 /**
1102 * Make a search link with some target namespaces
1103 *
1104 * @param string $term
1105 * @param array $namespaces Ignored
1106 * @param string $label Link's text
1107 * @param string $tooltip Link's tooltip
1108 * @param array $params Query string parameters
1109 * @return string HTML fragment
1110 */
1111 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1112 $opt = $params;
1113 foreach ( $namespaces as $n ) {
1114 $opt['ns' . $n] = 1;
1115 }
1116
1117 $stParams = array_merge(
1118 [
1119 'search' => $term,
1120 'fulltext' => $this->msg( 'search' )->text()
1121 ],
1122 $opt
1123 );
1124
1125 return Xml::element(
1126 'a',
1127 [
1128 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1129 'title' => $tooltip
1130 ],
1131 $label
1132 );
1133 }
1134
1135 /**
1136 * Check if query starts with image: prefix
1137 *
1138 * @param string $term The string to check
1139 * @return bool
1140 */
1141 protected function startsWithImage( $term ) {
1142 global $wgContLang;
1143
1144 $parts = explode( ':', $term );
1145 if ( count( $parts ) > 1 ) {
1146 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1147 }
1148
1149 return false;
1150 }
1151
1152 /**
1153 * @since 1.18
1154 *
1155 * @return SearchEngine
1156 */
1157 public function getSearchEngine() {
1158 if ( $this->searchEngine === null ) {
1159 $this->searchEngine = $this->searchEngineType ?
1160 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1161 MediaWikiServices::getInstance()->newSearchEngine();
1162 }
1163
1164 return $this->searchEngine;
1165 }
1166
1167 /**
1168 * Current search profile.
1169 * @return null|string
1170 */
1171 function getProfile() {
1172 return $this->profile;
1173 }
1174
1175 /**
1176 * Current namespaces.
1177 * @return array
1178 */
1179 function getNamespaces() {
1180 return $this->namespaces;
1181 }
1182
1183 /**
1184 * Users of hook SpecialSearchSetupEngine can use this to
1185 * add more params to links to not lose selection when
1186 * user navigates search results.
1187 * @since 1.18
1188 *
1189 * @param string $key
1190 * @param mixed $value
1191 */
1192 public function setExtraParam( $key, $value ) {
1193 $this->extraParams[$key] = $value;
1194 }
1195
1196 protected function getGroupName() {
1197 return 'pages';
1198 }
1199 }