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