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