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