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