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