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