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