Merge "Make RefreshLinksJob handle LinksUpdateConstructed hooks doing DB writes"
[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 $linkRenderer = $this->getLinkRenderer();
503
504 $snippet = $textMatches->getSuggestionSnippet() ?: null;
505 if ( $snippet !== null ) {
506 $snippet = new HtmlArmor( $snippet );
507 }
508
509 $suggest = $linkRenderer->makeKnownLink(
510 $this->getPageTitle(),
511 $snippet,
512 [ 'id' => 'mw-search-DYM-suggestion' ],
513 $stParams
514 );
515
516 # HTML of did you mean... search suggestion link
517 return Html::rawElement(
518 'div',
519 [ 'class' => 'searchdidyoumean' ],
520 $this->msg( 'search-suggest' )->rawParams( $suggest )->parse()
521 );
522 }
523
524 /**
525 * Generates HTML shown to user when their query has been internally rewritten,
526 * and the results of the rewritten query are being returned.
527 *
528 * @param string $term The users search input
529 * @param SearchResultSet $textMatches The response to the users initial search request
530 * @return string HTML linking the user to their original $term query, and the one
531 * suggested by $textMatches.
532 */
533 protected function getDidYouMeanRewrittenHtml( $term, SearchResultSet $textMatches ) {
534 // Showing results for '$rewritten'
535 // Search instead for '$orig'
536
537 $params = [ 'search' => $textMatches->getQueryAfterRewrite() ];
538 if ( $this->fulltext === null ) {
539 $params['fulltext'] = 'Search';
540 } else {
541 $params['fulltext'] = $this->fulltext;
542 }
543 $stParams = array_merge( $params, $this->powerSearchOptions() );
544
545 $linkRenderer = $this->getLinkRenderer();
546
547 $snippet = $textMatches->getQueryAfterRewriteSnippet() ?: null;
548 if ( $snippet !== null ) {
549 $snippet = new HtmlArmor( $snippet );
550 }
551
552 $rewritten = $linkRenderer->makeKnownLink(
553 $this->getPageTitle(),
554 $snippet,
555 [ 'id' => 'mw-search-DYM-rewritten' ],
556 $stParams
557 );
558
559 $stParams['search'] = $term;
560 $stParams['runsuggestion'] = 0;
561 $original = $linkRenderer->makeKnownLink(
562 $this->getPageTitle(),
563 $term,
564 [ 'id' => 'mw-search-DYM-original' ],
565 $stParams
566 );
567
568 return Html::rawElement(
569 'div',
570 [ 'class' => 'searchdidyoumean' ],
571 $this->msg( 'search-rewritten' )->rawParams( $rewritten, $original )->escaped()
572 );
573 }
574
575 /**
576 * @param Title $title
577 * @param int $num The number of search results found
578 * @param null|SearchResultSet $titleMatches Results from title search
579 * @param null|SearchResultSet $textMatches Results from text search
580 */
581 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
582 // show direct page/create link if applicable
583
584 // Check DBkey !== '' in case of fragment link only.
585 if ( is_null( $title ) || $title->getDBkey() === ''
586 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
587 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
588 ) {
589 // invalid title
590 // preserve the paragraph for margins etc...
591 $this->getOutput()->addHTML( '<p></p>' );
592
593 return;
594 }
595
596 $messageName = 'searchmenu-new-nocreate';
597 $linkClass = 'mw-search-createlink';
598
599 if ( !$title->isExternal() ) {
600 if ( $title->isKnown() ) {
601 $messageName = 'searchmenu-exists';
602 $linkClass = 'mw-search-exists';
603 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
604 $messageName = 'searchmenu-new';
605 }
606 }
607
608 $params = [
609 $messageName,
610 wfEscapeWikiText( $title->getPrefixedText() ),
611 Message::numParam( $num )
612 ];
613 Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
614
615 // Extensions using the hook might still return an empty $messageName
616 if ( $messageName ) {
617 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
618 } else {
619 // preserve the paragraph for margins etc...
620 $this->getOutput()->addHTML( '<p></p>' );
621 }
622 }
623
624 /**
625 * @param string $term
626 */
627 protected function setupPage( $term ) {
628 $out = $this->getOutput();
629 if ( strval( $term ) !== '' ) {
630 $out->setPageTitle( $this->msg( 'searchresults' ) );
631 $out->setHTMLTitle( $this->msg( 'pagetitle' )
632 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
633 ->inContentLanguage()->text()
634 );
635 }
636 // add javascript specific to special:search
637 $out->addModules( 'mediawiki.special.search' );
638 }
639
640 /**
641 * Return true if current search is a power (advanced) search
642 *
643 * @return bool
644 */
645 protected function isPowerSearch() {
646 return $this->profile === 'advanced';
647 }
648
649 /**
650 * Extract "power search" namespace settings from the request object,
651 * returning a list of index numbers to search.
652 *
653 * @param WebRequest $request
654 * @return array
655 */
656 protected function powerSearch( &$request ) {
657 $arr = [];
658 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
659 if ( $request->getCheck( 'ns' . $ns ) ) {
660 $arr[] = $ns;
661 }
662 }
663
664 return $arr;
665 }
666
667 /**
668 * Reconstruct the 'power search' options for links
669 *
670 * @return array
671 */
672 protected function powerSearchOptions() {
673 $opt = [];
674 if ( !$this->isPowerSearch() ) {
675 $opt['profile'] = $this->profile;
676 } else {
677 foreach ( $this->namespaces as $n ) {
678 $opt['ns' . $n] = 1;
679 }
680 }
681
682 return $opt + $this->extraParams;
683 }
684
685 /**
686 * Save namespace preferences when we're supposed to
687 *
688 * @return bool Whether we wrote something
689 */
690 protected function saveNamespaces() {
691 $user = $this->getUser();
692 $request = $this->getRequest();
693
694 if ( $user->isLoggedIn() &&
695 $user->matchEditToken(
696 $request->getVal( 'nsRemember' ),
697 'searchnamespace',
698 $request
699 ) && !wfReadOnly()
700 ) {
701 // Reset namespace preferences: namespaces are not searched
702 // when they're not mentioned in the URL parameters.
703 foreach ( MWNamespace::getValidNamespaces() as $n ) {
704 $user->setOption( 'searchNs' . $n, false );
705 }
706 // The request parameters include all the namespaces to be searched.
707 // Even if they're the same as an existing profile, they're not eaten.
708 foreach ( $this->namespaces as $n ) {
709 $user->setOption( 'searchNs' . $n, true );
710 }
711
712 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
713 $user->saveSettings();
714 } );
715
716 return true;
717 }
718
719 return false;
720 }
721
722 /**
723 * Show whole set of results
724 *
725 * @param SearchResultSet $matches
726 * @param string $interwiki Interwiki name
727 *
728 * @return string
729 */
730 protected function showMatches( $matches, $interwiki = null ) {
731 global $wgContLang;
732
733 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
734 $out = '';
735 $result = $matches->next();
736 $pos = $this->offset;
737
738 if ( $result && $interwiki ) {
739 $out .= $this->interwikiHeader( $interwiki, $matches );
740 }
741
742 $out .= "<ul class='mw-search-results'>\n";
743 $widget = new \MediaWiki\Widget\Search\FullSearchResultWidget(
744 $this,
745 $this->getLinkRenderer()
746 );
747 while ( $result ) {
748 $out .= $widget->render( $result, $terms, $pos++ );
749 $result = $matches->next();
750 }
751 $out .= "</ul>\n";
752
753 // convert the whole thing to desired language variant
754 $out = $wgContLang->convert( $out );
755
756 return $out;
757 }
758
759 /**
760 * Extract custom captions from search-interwiki-custom message
761 */
762 protected function getCustomCaptions() {
763 if ( is_null( $this->customCaptions ) ) {
764 $this->customCaptions = [];
765 // format per line <iwprefix>:<caption>
766 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
767 foreach ( $customLines as $line ) {
768 $parts = explode( ":", $line, 2 );
769 if ( count( $parts ) == 2 ) { // validate line
770 $this->customCaptions[$parts[0]] = $parts[1];
771 }
772 }
773 }
774 }
775
776 /**
777 * Show results from other wikis
778 *
779 * @param SearchResultSet|array $matches
780 * @param string $terms
781 *
782 * @return string
783 */
784 protected function showInterwiki( $matches, $terms ) {
785 global $wgContLang;
786
787 // work out custom project captions
788 $this->getCustomCaptions();
789
790 if ( !is_array( $matches ) ) {
791 $matches = [ $matches ];
792 }
793
794 $iwResults = [];
795 foreach ( $matches as $set ) {
796 $result = $set->next();
797 while ( $result ) {
798 if ( !$result->isBrokenTitle() ) {
799 $iwResults[$result->getTitle()->getInterwiki()][] = $result;
800 }
801 $result = $set->next();
802 }
803 }
804
805 $out = '';
806 $widget = new MediaWiki\Widget\Search\SimpleSearchResultWidget(
807 $this,
808 $this->getLinkRenderer()
809 );
810 foreach ( $iwResults as $iwPrefix => $results ) {
811 $out .= $this->iwHeaderHtml( $iwPrefix, $terms );
812 $out .= "<ul class='mw-search-iwresults'>";
813 foreach ( $results as $result ) {
814 // This makes the bold asumption interwiki results are never paginated.
815 // That's currently true, but could change at some point?
816 $out .= $widget->render( $result, $terms, 0 );
817 }
818 $out .= "</ul>";
819 }
820
821 $out =
822 "<div id='mw-search-interwiki'>" .
823 "<div id='mw-search-interwiki-caption'>" .
824 $this->msg( 'search-interwiki-caption' )->escaped() .
825 "</div>" .
826 $out .
827 "</div>";
828
829 // convert the whole thing to desired language variant
830 return $wgContLang->convert( $out );
831 }
832
833 /**
834 * @param string $iwPrefix The interwiki prefix to render a header for
835 * @param string $terms The user-provided search terms
836 */
837 protected function iwHeaderHtml( $iwPrefix, $terms ) {
838 if ( isset( $this->customCaptions[$iwPrefix] ) ) {
839 $caption = $this->customCaptions[$iwPrefix];
840 } else {
841 $iwLookup = MediaWiki\MediaWikiServices::getInstance()->getInterwikiLookup();
842 $interwiki = $iwLookup->fetch( $iwPrefix );
843 $parsed = wfParseUrl( wfExpandUrl( $interwiki ? $interwiki->getURL() : '/' ) );
844 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
845 }
846 $searchLink = Linker::linkKnown(
847 Title::newFromText( "$iwPrefix:Special:Search" ),
848 $this->msg( 'search-interwiki-more' )->text(),
849 [],
850 [
851 'search' => $terms,
852 'fulltext' => 1,
853 ]
854 );
855 return
856 "<div class='mw-search-interwiki-project'>" .
857 "<span class='mw-search-interwiki-more'>{$searchLink}</span>" .
858 $caption .
859 "</div>";
860 }
861
862 /**
863 * Generates the power search box at [[Special:Search]]
864 *
865 * @param string $term Search term
866 * @param array $opts
867 * @return string HTML form
868 */
869 protected function powerSearchBox( $term, $opts ) {
870 global $wgContLang;
871
872 // Groups namespaces into rows according to subject
873 $rows = [];
874 foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
875 $subject = MWNamespace::getSubject( $namespace );
876 if ( !array_key_exists( $subject, $rows ) ) {
877 $rows[$subject] = "";
878 }
879
880 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
881 if ( $name == '' ) {
882 $name = $this->msg( 'blanknamespace' )->text();
883 }
884
885 $rows[$subject] .=
886 Xml::openElement( 'td' ) .
887 Xml::checkLabel(
888 $name,
889 "ns{$namespace}",
890 "mw-search-ns{$namespace}",
891 in_array( $namespace, $this->namespaces )
892 ) .
893 Xml::closeElement( 'td' );
894 }
895
896 $rows = array_values( $rows );
897 $numRows = count( $rows );
898
899 // Lays out namespaces in multiple floating two-column tables so they'll
900 // be arranged nicely while still accommodating different screen widths
901 $namespaceTables = '';
902 for ( $i = 0; $i < $numRows; $i += 4 ) {
903 $namespaceTables .= Xml::openElement( 'table' );
904
905 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
906 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
907 }
908
909 $namespaceTables .= Xml::closeElement( 'table' );
910 }
911
912 $showSections = [ 'namespaceTables' => $namespaceTables ];
913
914 Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
915
916 $hidden = '';
917 foreach ( $opts as $key => $value ) {
918 $hidden .= Html::hidden( $key, $value );
919 }
920
921 # Stuff to feed saveNamespaces()
922 $remember = '';
923 $user = $this->getUser();
924 if ( $user->isLoggedIn() ) {
925 $remember .= Xml::checkLabel(
926 $this->msg( 'powersearch-remember' )->text(),
927 'nsRemember',
928 'mw-search-powersearch-remember',
929 false,
930 // The token goes here rather than in a hidden field so it
931 // is only sent when necessary (not every form submission).
932 [ 'value' => $user->getEditToken(
933 'searchnamespace',
934 $this->getRequest()
935 ) ]
936 );
937 }
938
939 // Return final output
940 return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
941 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
942 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
943 Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
944 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
945 implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
946 $hidden .
947 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
948 $remember .
949 Xml::closeElement( 'fieldset' );
950 }
951
952 /**
953 * @return array
954 */
955 protected function getSearchProfiles() {
956 // Builds list of Search Types (profiles)
957 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
958 $defaultNs = $this->searchConfig->defaultNamespaces();
959 $profiles = [
960 'default' => [
961 'message' => 'searchprofile-articles',
962 'tooltip' => 'searchprofile-articles-tooltip',
963 'namespaces' => $defaultNs,
964 'namespace-messages' => $this->searchConfig->namespacesAsText(
965 $defaultNs
966 ),
967 ],
968 'images' => [
969 'message' => 'searchprofile-images',
970 'tooltip' => 'searchprofile-images-tooltip',
971 'namespaces' => [ NS_FILE ],
972 ],
973 'all' => [
974 'message' => 'searchprofile-everything',
975 'tooltip' => 'searchprofile-everything-tooltip',
976 'namespaces' => $nsAllSet,
977 ],
978 'advanced' => [
979 'message' => 'searchprofile-advanced',
980 'tooltip' => 'searchprofile-advanced-tooltip',
981 'namespaces' => self::NAMESPACES_CURRENT,
982 ]
983 ];
984
985 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
986
987 foreach ( $profiles as &$data ) {
988 if ( !is_array( $data['namespaces'] ) ) {
989 continue;
990 }
991 sort( $data['namespaces'] );
992 }
993
994 return $profiles;
995 }
996
997 /**
998 * @param string $term
999 * @return string
1000 */
1001 protected function searchProfileTabs( $term ) {
1002 $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1003 Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1004
1005 $bareterm = $term;
1006 if ( $this->startsWithImage( $term ) ) {
1007 // Deletes prefixes
1008 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1009 }
1010
1011 $profiles = $this->getSearchProfiles();
1012 $lang = $this->getLanguage();
1013
1014 // Outputs XML for Search Types
1015 $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1016 $out .= Xml::openElement( 'ul' );
1017 foreach ( $profiles as $id => $profile ) {
1018 if ( !isset( $profile['parameters'] ) ) {
1019 $profile['parameters'] = [];
1020 }
1021 $profile['parameters']['profile'] = $id;
1022
1023 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1024 $lang->commaList( $profile['namespace-messages'] ) : null;
1025 $out .= Xml::tags(
1026 'li',
1027 [
1028 'class' => $this->profile === $id ? 'current' : 'normal'
1029 ],
1030 $this->makeSearchLink(
1031 $bareterm,
1032 [],
1033 $this->msg( $profile['message'] )->text(),
1034 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1035 $profile['parameters']
1036 )
1037 );
1038 }
1039 $out .= Xml::closeElement( 'ul' );
1040 $out .= Xml::closeElement( 'div' );
1041 $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1042 $out .= Xml::closeElement( 'div' );
1043
1044 return $out;
1045 }
1046
1047 /**
1048 * @param string $term Search term
1049 * @return string
1050 */
1051 protected function searchOptions( $term ) {
1052 $out = '';
1053 $opts = [];
1054 $opts['profile'] = $this->profile;
1055
1056 if ( $this->isPowerSearch() ) {
1057 $out .= $this->powerSearchBox( $term, $opts );
1058 } else {
1059 $form = '';
1060 Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1061 $out .= $form;
1062 }
1063
1064 return $out;
1065 }
1066
1067 /**
1068 * @param string $term
1069 * @param int $resultsShown
1070 * @param int $totalNum
1071 * @return string
1072 */
1073 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1074 $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1075 'id' => 'searchText',
1076 'name' => 'search',
1077 'autofocus' => trim( $term ) === '',
1078 'value' => $term,
1079 'dataLocation' => 'content',
1080 'infusable' => true,
1081 ] );
1082
1083 $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1084 'type' => 'submit',
1085 'label' => $this->msg( 'searchbutton' )->text(),
1086 'flags' => [ 'progressive', 'primary' ],
1087 ] ), [
1088 'align' => 'top',
1089 ] );
1090
1091 $out =
1092 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1093 Html::hidden( 'profile', $this->profile ) .
1094 Html::hidden( 'fulltext', 'Search' ) .
1095 $layout;
1096
1097 // Results-info
1098 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1099 $top = $this->msg( 'search-showingresults' )
1100 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1101 ->numParams( $resultsShown )
1102 ->parse();
1103 $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1104 }
1105
1106 return $out;
1107 }
1108
1109 /**
1110 * Make a search link with some target namespaces
1111 *
1112 * @param string $term
1113 * @param array $namespaces Ignored
1114 * @param string $label Link's text
1115 * @param string $tooltip Link's tooltip
1116 * @param array $params Query string parameters
1117 * @return string HTML fragment
1118 */
1119 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1120 $opt = $params;
1121 foreach ( $namespaces as $n ) {
1122 $opt['ns' . $n] = 1;
1123 }
1124
1125 $stParams = array_merge(
1126 [
1127 'search' => $term,
1128 'fulltext' => $this->msg( 'search' )->text()
1129 ],
1130 $opt
1131 );
1132
1133 return Xml::element(
1134 'a',
1135 [
1136 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1137 'title' => $tooltip
1138 ],
1139 $label
1140 );
1141 }
1142
1143 /**
1144 * Check if query starts with image: prefix
1145 *
1146 * @param string $term The string to check
1147 * @return bool
1148 */
1149 protected function startsWithImage( $term ) {
1150 global $wgContLang;
1151
1152 $parts = explode( ':', $term );
1153 if ( count( $parts ) > 1 ) {
1154 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1155 }
1156
1157 return false;
1158 }
1159
1160 /**
1161 * @since 1.18
1162 *
1163 * @return SearchEngine
1164 */
1165 public function getSearchEngine() {
1166 if ( $this->searchEngine === null ) {
1167 $this->searchEngine = $this->searchEngineType ?
1168 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1169 MediaWikiServices::getInstance()->newSearchEngine();
1170 }
1171
1172 return $this->searchEngine;
1173 }
1174
1175 /**
1176 * Current search profile.
1177 * @return null|string
1178 */
1179 function getProfile() {
1180 return $this->profile;
1181 }
1182
1183 /**
1184 * Current namespaces.
1185 * @return array
1186 */
1187 function getNamespaces() {
1188 return $this->namespaces;
1189 }
1190
1191 /**
1192 * Users of hook SpecialSearchSetupEngine can use this to
1193 * add more params to links to not lose selection when
1194 * user navigates search results.
1195 * @since 1.18
1196 *
1197 * @param string $key
1198 * @param mixed $value
1199 */
1200 public function setExtraParam( $key, $value ) {
1201 $this->extraParams[$key] = $value;
1202 }
1203
1204 protected function getGroupName() {
1205 return 'pages';
1206 }
1207 }