Merge "EditPage: Show a different label for the button on create vs. modify"
[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 $out->addHTML( $this->showMatches( $textMatches ) );
407 }
408
409 // show secondary interwiki results if any
410 if ( $textMatches->hasInterwikiResults( SearchResultSet::SECONDARY_RESULTS ) ) {
411 $out->addHTML( $this->showInterwiki( $textMatches->getInterwikiResults(
412 SearchResultSet::SECONDARY_RESULTS ), $term ) );
413 }
414 }
415
416 $hasOtherResults = $textMatches &&
417 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
418
419 if ( $num === 0 ) {
420 if ( $textStatus ) {
421 $out->addHTML( '<div class="error">' .
422 $textStatus->getMessage( 'search-error' ) . '</div>' );
423 } else {
424 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
425 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>",
426 [ $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
427 wfEscapeWikiText( $term )
428 ] );
429 }
430 }
431
432 if ( $hasOtherResults ) {
433 foreach ( $textMatches->getInterwikiResults( SearchResultSet::INLINE_RESULTS )
434 as $interwiki => $interwikiResult ) {
435 if ( $interwikiResult instanceof Status || $interwikiResult->numRows() == 0 ) {
436 // ignore bad interwikis for now
437 continue;
438 }
439 // TODO: wiki header
440 $out->addHTML( $this->showMatches( $interwikiResult, $interwiki ) );
441 }
442 }
443
444 if ( $textMatches ) {
445 $textMatches->free();
446 }
447
448 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
449
450 if ( $prevnext ) {
451 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
452 }
453
454 $out->addHTML( "</div>" );
455
456 Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
457
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, $result );
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( $result, $terms, $position ) {
754
755 if ( $result->isBrokenTitle() ) {
756 return '';
757 }
758
759 $title = $result->getTitle();
760
761 $titleSnippet = $result->getTitleSnippet();
762
763 if ( $titleSnippet == '' ) {
764 $titleSnippet = null;
765 }
766
767 $link_t = clone $title;
768 $query = [];
769
770 Hooks::run( 'ShowSearchHitTitle',
771 [ &$link_t, &$titleSnippet, $result, $terms, $this, &$query ] );
772
773 $link = Linker::linkKnown(
774 $link_t,
775 $titleSnippet,
776 [ 'data-serp-pos' => $position ], // HTML attributes
777 $query
778 );
779
780 // If page content is not readable, just return the title.
781 // This is not quite safe, but better than showing excerpts from non-readable pages
782 // Note that hiding the entry entirely would screw up paging.
783 if ( !$title->userCan( 'read', $this->getUser() ) ) {
784 return "<li>{$link}</li>\n";
785 }
786
787 // If the page doesn't *exist*... our search index is out of date.
788 // The least confusing at this point is to drop the result.
789 // You may get less results, but... oh well. :P
790 if ( $result->isMissingRevision() ) {
791 return '';
792 }
793
794 // format redirects / relevant sections
795 $redirectTitle = $result->getRedirectTitle();
796 $redirectText = $result->getRedirectSnippet();
797 $sectionTitle = $result->getSectionTitle();
798 $sectionText = $result->getSectionSnippet();
799 $categorySnippet = $result->getCategorySnippet();
800
801 $redirect = '';
802 if ( !is_null( $redirectTitle ) ) {
803 if ( $redirectText == '' ) {
804 $redirectText = null;
805 }
806
807 $redirect = "<span class='searchalttitle'>" .
808 $this->msg( 'search-redirect' )->rawParams(
809 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
810 "</span>";
811 }
812
813 $section = '';
814 if ( !is_null( $sectionTitle ) ) {
815 if ( $sectionText == '' ) {
816 $sectionText = null;
817 }
818
819 $section = "<span class='searchalttitle'>" .
820 $this->msg( 'search-section' )->rawParams(
821 Linker::linkKnown( $sectionTitle, $sectionText ) )->text() .
822 "</span>";
823 }
824
825 $category = '';
826 if ( $categorySnippet ) {
827 $category = "<span class='searchalttitle'>" .
828 $this->msg( 'search-category' )->rawParams( $categorySnippet )->text() .
829 "</span>";
830 }
831
832 // format text extract
833 $extract = "<div class='searchresult'>" . $result->getTextSnippet( $terms ) . "</div>";
834
835 $lang = $this->getLanguage();
836
837 // format description
838 $byteSize = $result->getByteSize();
839 $wordCount = $result->getWordCount();
840 $timestamp = $result->getTimestamp();
841 $size = $this->msg( 'search-result-size', $lang->formatSize( $byteSize ) )
842 ->numParams( $wordCount )->escaped();
843
844 if ( $title->getNamespace() == NS_CATEGORY ) {
845 $cat = Category::newFromTitle( $title );
846 $size = $this->msg( 'search-result-category-size' )
847 ->numParams( $cat->getPageCount(), $cat->getSubcatCount(), $cat->getFileCount() )
848 ->escaped();
849 }
850
851 $date = $lang->userTimeAndDate( $timestamp, $this->getUser() );
852
853 $fileMatch = '';
854 // Include a thumbnail for media files...
855 if ( $title->getNamespace() == NS_FILE ) {
856 $img = $result->getFile();
857 $img = $img ?: wfFindFile( $title );
858 if ( $result->isFileMatch() ) {
859 $fileMatch = "<span class='searchalttitle'>" .
860 $this->msg( 'search-file-match' )->escaped() . "</span>";
861 }
862 if ( $img ) {
863 $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
864 if ( $thumb ) {
865 $desc = $this->msg( 'parentheses' )->rawParams( $img->getShortDesc() )->escaped();
866 // Float doesn't seem to interact well with the bullets.
867 // Table messes up vertical alignment of the bullets.
868 // Bullets are therefore disabled (didn't look great anyway).
869 return "<li>" .
870 '<table class="searchResultImage">' .
871 '<tr>' .
872 '<td style="width: 120px; text-align: center; vertical-align: top;">' .
873 $thumb->toHtml( [ 'desc-link' => true ] ) .
874 '</td>' .
875 '<td style="vertical-align: top;">' .
876 "{$link} {$redirect} {$category} {$section} {$fileMatch}" .
877 $extract .
878 "<div class='mw-search-result-data'>{$desc} - {$date}</div>" .
879 '</td>' .
880 '</tr>' .
881 '</table>' .
882 "</li>\n";
883 }
884 }
885 }
886
887 $html = null;
888
889 $score = '';
890 $related = '';
891 if ( Hooks::run( 'ShowSearchHit', [
892 $this, $result, $terms,
893 &$link, &$redirect, &$section, &$extract,
894 &$score, &$size, &$date, &$related,
895 &$html
896 ] ) ) {
897 $html = "<li><div class='mw-search-result-heading'>" .
898 "{$link} {$redirect} {$category} {$section} {$fileMatch}</div> {$extract}\n" .
899 "<div class='mw-search-result-data'>{$size} - {$date}</div>" .
900 "</li>\n";
901 }
902
903 return $html;
904 }
905
906 /**
907 * Extract custom captions from search-interwiki-custom message
908 */
909 protected function getCustomCaptions() {
910 if ( is_null( $this->customCaptions ) ) {
911 $this->customCaptions = [];
912 // format per line <iwprefix>:<caption>
913 $customLines = explode( "\n", $this->msg( 'search-interwiki-custom' )->text() );
914 foreach ( $customLines as $line ) {
915 $parts = explode( ":", $line, 2 );
916 if ( count( $parts ) == 2 ) { // validate line
917 $this->customCaptions[$parts[0]] = $parts[1];
918 }
919 }
920 }
921 }
922
923 /**
924 * Show results from other wikis
925 *
926 * @param SearchResultSet|array $matches
927 * @param string $query
928 *
929 * @return string
930 */
931 protected function showInterwiki( $matches, $query ) {
932 global $wgContLang;
933
934 $out = "<div id='mw-search-interwiki'><div id='mw-search-interwiki-caption'>" .
935 $this->msg( 'search-interwiki-caption' )->text() . "</div>\n";
936 $out .= "<ul class='mw-search-iwresults'>\n";
937
938 // work out custom project captions
939 $this->getCustomCaptions();
940
941 if ( !is_array( $matches ) ) {
942 $matches = [ $matches ];
943 }
944
945 foreach ( $matches as $set ) {
946 $prev = null;
947 $result = $set->next();
948 while ( $result ) {
949 $out .= $this->showInterwikiHit( $result, $prev, $query );
950 $prev = $result->getInterwikiPrefix();
951 $result = $set->next();
952 }
953 }
954
955 // @todo Should support paging in a non-confusing way (not sure how though, maybe via ajax)..
956 $out .= "</ul></div>\n";
957
958 // convert the whole thing to desired language variant
959 $out = $wgContLang->convert( $out );
960
961 return $out;
962 }
963
964 /**
965 * Show single interwiki link
966 *
967 * @param SearchResult $result
968 * @param string $lastInterwiki
969 * @param string $query
970 *
971 * @return string
972 */
973 protected function showInterwikiHit( $result, $lastInterwiki, $query ) {
974
975 if ( $result->isBrokenTitle() ) {
976 return '';
977 }
978
979 $title = $result->getTitle();
980
981 $titleSnippet = $result->getTitleSnippet();
982
983 if ( $titleSnippet == '' ) {
984 $titleSnippet = null;
985 }
986
987 $link = Linker::linkKnown(
988 $title,
989 $titleSnippet
990 );
991
992 // format redirect if any
993 $redirectTitle = $result->getRedirectTitle();
994 $redirectText = $result->getRedirectSnippet();
995 $redirect = '';
996 if ( !is_null( $redirectTitle ) ) {
997 if ( $redirectText == '' ) {
998 $redirectText = null;
999 }
1000
1001 $redirect = "<span class='searchalttitle'>" .
1002 $this->msg( 'search-redirect' )->rawParams(
1003 Linker::linkKnown( $redirectTitle, $redirectText ) )->text() .
1004 "</span>";
1005 }
1006
1007 $out = "";
1008 // display project name
1009 if ( is_null( $lastInterwiki ) || $lastInterwiki != $title->getInterwiki() ) {
1010 if ( array_key_exists( $title->getInterwiki(), $this->customCaptions ) ) {
1011 // captions from 'search-interwiki-custom'
1012 $caption = $this->customCaptions[$title->getInterwiki()];
1013 } else {
1014 // default is to show the hostname of the other wiki which might suck
1015 // if there are many wikis on one hostname
1016 $parsed = wfParseUrl( $title->getFullURL() );
1017 $caption = $this->msg( 'search-interwiki-default', $parsed['host'] )->text();
1018 }
1019 // "more results" link (special page stuff could be localized, but we might not know target lang)
1020 $searchTitle = Title::newFromText( $title->getInterwiki() . ":Special:Search" );
1021 $searchLink = Linker::linkKnown(
1022 $searchTitle,
1023 $this->msg( 'search-interwiki-more' )->text(),
1024 [],
1025 [
1026 'search' => $query,
1027 'fulltext' => 'Search'
1028 ]
1029 );
1030 $out .= "</ul><div class='mw-search-interwiki-project'><span class='mw-search-interwiki-more'>
1031 {$searchLink}</span>{$caption}</div>\n<ul>";
1032 }
1033
1034 $out .= "<li>{$link} {$redirect}</li>\n";
1035
1036 return $out;
1037 }
1038
1039 /**
1040 * Generates the power search box at [[Special:Search]]
1041 *
1042 * @param string $term Search term
1043 * @param array $opts
1044 * @return string HTML form
1045 */
1046 protected function powerSearchBox( $term, $opts ) {
1047 global $wgContLang;
1048
1049 // Groups namespaces into rows according to subject
1050 $rows = [];
1051 foreach ( $this->searchConfig->searchableNamespaces() as $namespace => $name ) {
1052 $subject = MWNamespace::getSubject( $namespace );
1053 if ( !array_key_exists( $subject, $rows ) ) {
1054 $rows[$subject] = "";
1055 }
1056
1057 $name = $wgContLang->getConverter()->convertNamespace( $namespace );
1058 if ( $name == '' ) {
1059 $name = $this->msg( 'blanknamespace' )->text();
1060 }
1061
1062 $rows[$subject] .=
1063 Xml::openElement( 'td' ) .
1064 Xml::checkLabel(
1065 $name,
1066 "ns{$namespace}",
1067 "mw-search-ns{$namespace}",
1068 in_array( $namespace, $this->namespaces )
1069 ) .
1070 Xml::closeElement( 'td' );
1071 }
1072
1073 $rows = array_values( $rows );
1074 $numRows = count( $rows );
1075
1076 // Lays out namespaces in multiple floating two-column tables so they'll
1077 // be arranged nicely while still accommodating different screen widths
1078 $namespaceTables = '';
1079 for ( $i = 0; $i < $numRows; $i += 4 ) {
1080 $namespaceTables .= Xml::openElement( 'table' );
1081
1082 for ( $j = $i; $j < $i + 4 && $j < $numRows; $j++ ) {
1083 $namespaceTables .= Xml::tags( 'tr', null, $rows[$j] );
1084 }
1085
1086 $namespaceTables .= Xml::closeElement( 'table' );
1087 }
1088
1089 $showSections = [ 'namespaceTables' => $namespaceTables ];
1090
1091 Hooks::run( 'SpecialSearchPowerBox', [ &$showSections, $term, $opts ] );
1092
1093 $hidden = '';
1094 foreach ( $opts as $key => $value ) {
1095 $hidden .= Html::hidden( $key, $value );
1096 }
1097
1098 # Stuff to feed saveNamespaces()
1099 $remember = '';
1100 $user = $this->getUser();
1101 if ( $user->isLoggedIn() ) {
1102 $remember .= Xml::checkLabel(
1103 $this->msg( 'powersearch-remember' )->text(),
1104 'nsRemember',
1105 'mw-search-powersearch-remember',
1106 false,
1107 // The token goes here rather than in a hidden field so it
1108 // is only sent when necessary (not every form submission).
1109 [ 'value' => $user->getEditToken(
1110 'searchnamespace',
1111 $this->getRequest()
1112 ) ]
1113 );
1114 }
1115
1116 // Return final output
1117 return Xml::openElement( 'fieldset', [ 'id' => 'mw-searchoptions' ] ) .
1118 Xml::element( 'legend', null, $this->msg( 'powersearch-legend' )->text() ) .
1119 Xml::tags( 'h4', null, $this->msg( 'powersearch-ns' )->parse() ) .
1120 Xml::element( 'div', [ 'id' => 'mw-search-togglebox' ], '', false ) .
1121 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1122 implode( Xml::element( 'div', [ 'class' => 'divider' ], '', false ), $showSections ) .
1123 $hidden .
1124 Xml::element( 'div', [ 'class' => 'divider' ], '', false ) .
1125 $remember .
1126 Xml::closeElement( 'fieldset' );
1127 }
1128
1129 /**
1130 * @return array
1131 */
1132 protected function getSearchProfiles() {
1133 // Builds list of Search Types (profiles)
1134 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
1135 $defaultNs = $this->searchConfig->defaultNamespaces();
1136 $profiles = [
1137 'default' => [
1138 'message' => 'searchprofile-articles',
1139 'tooltip' => 'searchprofile-articles-tooltip',
1140 'namespaces' => $defaultNs,
1141 'namespace-messages' => $this->searchConfig->namespacesAsText(
1142 $defaultNs
1143 ),
1144 ],
1145 'images' => [
1146 'message' => 'searchprofile-images',
1147 'tooltip' => 'searchprofile-images-tooltip',
1148 'namespaces' => [ NS_FILE ],
1149 ],
1150 'all' => [
1151 'message' => 'searchprofile-everything',
1152 'tooltip' => 'searchprofile-everything-tooltip',
1153 'namespaces' => $nsAllSet,
1154 ],
1155 'advanced' => [
1156 'message' => 'searchprofile-advanced',
1157 'tooltip' => 'searchprofile-advanced-tooltip',
1158 'namespaces' => self::NAMESPACES_CURRENT,
1159 ]
1160 ];
1161
1162 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
1163
1164 foreach ( $profiles as &$data ) {
1165 if ( !is_array( $data['namespaces'] ) ) {
1166 continue;
1167 }
1168 sort( $data['namespaces'] );
1169 }
1170
1171 return $profiles;
1172 }
1173
1174 /**
1175 * @param string $term
1176 * @return string
1177 */
1178 protected function searchProfileTabs( $term ) {
1179 $out = Html::element( 'div', [ 'class' => 'mw-search-visualclear' ] ) .
1180 Xml::openElement( 'div', [ 'class' => 'mw-search-profile-tabs' ] );
1181
1182 $bareterm = $term;
1183 if ( $this->startsWithImage( $term ) ) {
1184 // Deletes prefixes
1185 $bareterm = substr( $term, strpos( $term, ':' ) + 1 );
1186 }
1187
1188 $profiles = $this->getSearchProfiles();
1189 $lang = $this->getLanguage();
1190
1191 // Outputs XML for Search Types
1192 $out .= Xml::openElement( 'div', [ 'class' => 'search-types' ] );
1193 $out .= Xml::openElement( 'ul' );
1194 foreach ( $profiles as $id => $profile ) {
1195 if ( !isset( $profile['parameters'] ) ) {
1196 $profile['parameters'] = [];
1197 }
1198 $profile['parameters']['profile'] = $id;
1199
1200 $tooltipParam = isset( $profile['namespace-messages'] ) ?
1201 $lang->commaList( $profile['namespace-messages'] ) : null;
1202 $out .= Xml::tags(
1203 'li',
1204 [
1205 'class' => $this->profile === $id ? 'current' : 'normal'
1206 ],
1207 $this->makeSearchLink(
1208 $bareterm,
1209 [],
1210 $this->msg( $profile['message'] )->text(),
1211 $this->msg( $profile['tooltip'], $tooltipParam )->text(),
1212 $profile['parameters']
1213 )
1214 );
1215 }
1216 $out .= Xml::closeElement( 'ul' );
1217 $out .= Xml::closeElement( 'div' );
1218 $out .= Xml::element( 'div', [ 'style' => 'clear:both' ], '', false );
1219 $out .= Xml::closeElement( 'div' );
1220
1221 return $out;
1222 }
1223
1224 /**
1225 * @param string $term Search term
1226 * @return string
1227 */
1228 protected function searchOptions( $term ) {
1229 $out = '';
1230 $opts = [];
1231 $opts['profile'] = $this->profile;
1232
1233 if ( $this->isPowerSearch() ) {
1234 $out .= $this->powerSearchBox( $term, $opts );
1235 } else {
1236 $form = '';
1237 Hooks::run( 'SpecialSearchProfileForm', [ $this, &$form, $this->profile, $term, $opts ] );
1238 $out .= $form;
1239 }
1240
1241 return $out;
1242 }
1243
1244 /**
1245 * @param string $term
1246 * @param int $resultsShown
1247 * @param int $totalNum
1248 * @return string
1249 */
1250 protected function shortDialog( $term, $resultsShown, $totalNum ) {
1251 $searchWidget = new MediaWiki\Widget\SearchInputWidget( [
1252 'id' => 'searchText',
1253 'name' => 'search',
1254 'autofocus' => trim( $term ) === '',
1255 'value' => $term,
1256 'dataLocation' => 'content',
1257 'infusable' => true,
1258 ] );
1259
1260 $layout = new OOUI\ActionFieldLayout( $searchWidget, new OOUI\ButtonInputWidget( [
1261 'type' => 'submit',
1262 'label' => $this->msg( 'searchbutton' )->text(),
1263 'flags' => [ 'progressive', 'primary' ],
1264 ] ), [
1265 'align' => 'top',
1266 ] );
1267
1268 $out =
1269 Html::hidden( 'title', $this->getPageTitle()->getPrefixedText() ) .
1270 Html::hidden( 'profile', $this->profile ) .
1271 Html::hidden( 'fulltext', 'Search' ) .
1272 $layout;
1273
1274 // Results-info
1275 if ( $totalNum > 0 && $this->offset < $totalNum ) {
1276 $top = $this->msg( 'search-showingresults' )
1277 ->numParams( $this->offset + 1, $this->offset + $resultsShown, $totalNum )
1278 ->numParams( $resultsShown )
1279 ->parse();
1280 $out .= Xml::tags( 'div', [ 'class' => 'results-info' ], $top );
1281 }
1282
1283 return $out;
1284 }
1285
1286 /**
1287 * Make a search link with some target namespaces
1288 *
1289 * @param string $term
1290 * @param array $namespaces Ignored
1291 * @param string $label Link's text
1292 * @param string $tooltip Link's tooltip
1293 * @param array $params Query string parameters
1294 * @return string HTML fragment
1295 */
1296 protected function makeSearchLink( $term, $namespaces, $label, $tooltip, $params = [] ) {
1297 $opt = $params;
1298 foreach ( $namespaces as $n ) {
1299 $opt['ns' . $n] = 1;
1300 }
1301
1302 $stParams = array_merge(
1303 [
1304 'search' => $term,
1305 'fulltext' => $this->msg( 'search' )->text()
1306 ],
1307 $opt
1308 );
1309
1310 return Xml::element(
1311 'a',
1312 [
1313 'href' => $this->getPageTitle()->getLocalURL( $stParams ),
1314 'title' => $tooltip
1315 ],
1316 $label
1317 );
1318 }
1319
1320 /**
1321 * Check if query starts with image: prefix
1322 *
1323 * @param string $term The string to check
1324 * @return bool
1325 */
1326 protected function startsWithImage( $term ) {
1327 global $wgContLang;
1328
1329 $parts = explode( ':', $term );
1330 if ( count( $parts ) > 1 ) {
1331 return $wgContLang->getNsIndex( $parts[0] ) == NS_FILE;
1332 }
1333
1334 return false;
1335 }
1336
1337 /**
1338 * Check if query starts with all: prefix
1339 *
1340 * @param string $term The string to check
1341 * @return bool
1342 */
1343 protected function startsWithAll( $term ) {
1344
1345 $allkeyword = $this->msg( 'searchall' )->inContentLanguage()->text();
1346
1347 $parts = explode( ':', $term );
1348 if ( count( $parts ) > 1 ) {
1349 return $parts[0] == $allkeyword;
1350 }
1351
1352 return false;
1353 }
1354
1355 /**
1356 * @since 1.18
1357 *
1358 * @return SearchEngine
1359 */
1360 public function getSearchEngine() {
1361 if ( $this->searchEngine === null ) {
1362 $this->searchEngine = $this->searchEngineType ?
1363 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
1364 MediaWikiServices::getInstance()->newSearchEngine();
1365 }
1366
1367 return $this->searchEngine;
1368 }
1369
1370 /**
1371 * Current search profile.
1372 * @return null|string
1373 */
1374 function getProfile() {
1375 return $this->profile;
1376 }
1377
1378 /**
1379 * Current namespaces.
1380 * @return array
1381 */
1382 function getNamespaces() {
1383 return $this->namespaces;
1384 }
1385
1386 /**
1387 * Users of hook SpecialSearchSetupEngine can use this to
1388 * add more params to links to not lose selection when
1389 * user navigates search results.
1390 * @since 1.18
1391 *
1392 * @param string $key
1393 * @param mixed $value
1394 */
1395 public function setExtraParam( $key, $value ) {
1396 $this->extraParams[$key] = $value;
1397 }
1398
1399 protected function getGroupName() {
1400 return 'pages';
1401 }
1402 }