Unbreak extensions using SpecialSearchResults hook
[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 use MediaWiki\Widget\Search\BasicSearchResultSetWidget;
28 use MediaWiki\Widget\Search\InterwikiSearchResultSetWidget;
29 use MediaWiki\Widget\Search\FullSearchResultWidget;
30 use MediaWiki\Widget\Search\SimpleSearchResultWidget;
31
32 /**
33 * implements Special:Search - Run text & title search and display the output
34 * @ingroup SpecialPage
35 */
36 class SpecialSearch extends SpecialPage {
37 /**
38 * Current search profile. Search profile is just a name that identifies
39 * the active search tab on the search page (content, discussions...)
40 * For users tt replaces the set of enabled namespaces from the query
41 * string when applicable. Extensions can add new profiles with hooks
42 * with custom search options just for that profile.
43 * @var null|string
44 */
45 protected $profile;
46
47 /** @var SearchEngine Search engine */
48 protected $searchEngine;
49
50 /** @var string Search engine type, if not default */
51 protected $searchEngineType;
52
53 /** @var array For links */
54 protected $extraParams = [];
55
56 /**
57 * @var string The prefix url parameter. Set on the searcher and the
58 * is expected to treat it as prefix filter on titles.
59 */
60 protected $mPrefix;
61
62 /**
63 * @var int
64 */
65 protected $limit, $offset;
66
67 /**
68 * @var array
69 */
70 protected $namespaces;
71
72 /**
73 * @var string
74 */
75 protected $fulltext;
76
77 /**
78 * @var bool
79 */
80 protected $runSuggestion = true;
81
82 /**
83 * Search engine configurations.
84 * @var SearchEngineConfig
85 */
86 protected $searchConfig;
87
88 const NAMESPACES_CURRENT = 'sense';
89
90 public function __construct() {
91 parent::__construct( 'Search' );
92 $this->searchConfig = MediaWikiServices::getInstance()->getSearchEngineConfig();
93 }
94
95 /**
96 * Entry point
97 *
98 * @param string $par
99 */
100 public function execute( $par ) {
101 $request = $this->getRequest();
102 $out = $this->getOutput();
103
104 // Fetch the search term
105 $term = str_replace( "\n", " ", $request->getText( 'search' ) );
106
107 // Historically search terms have been accepted not only in the search query
108 // parameter, but also as part of the primary url. This can have PII implications
109 // in releasing page view data. As such issue a 301 redirect to the correct
110 // URL.
111 if ( strlen( $par ) && !strlen( $term ) ) {
112 $query = $request->getValues();
113 unset( $query['title'] );
114 // Strip underscores from title parameter; most of the time we'll want
115 // text form here. But don't strip underscores from actual text params!
116 $query['search'] = str_replace( '_', ' ', $par );
117 $out->redirect( $this->getPageTitle()->getFullURL( $query ), 301 );
118 return;
119 }
120
121 // Need to load selected namespaces before handling nsRemember
122 $this->load();
123 // TODO: This performs database actions on GET request, which is going to
124 // be a problem for our multi-datacenter work.
125 if ( !is_null( $request->getVal( 'nsRemember' ) ) ) {
126 $this->saveNamespaces();
127 // Remove the token from the URL to prevent the user from inadvertently
128 // exposing it (e.g. by pasting it into a public wiki page) or undoing
129 // later settings changes (e.g. by reloading the page).
130 $query = $request->getValues();
131 unset( $query['title'], $query['nsRemember'] );
132 $out->redirect( $this->getPageTitle()->getFullURL( $query ) );
133 return;
134 }
135
136 $this->searchEngineType = $request->getVal( 'srbackend' );
137 if (
138 !$request->getVal( 'fulltext' ) &&
139 $request->getVal( 'offset' ) === null
140 ) {
141 $url = $this->goResult( $term );
142 if ( $url !== null ) {
143 // successful 'go'
144 $out->redirect( $url );
145 return;
146 }
147 }
148
149 $this->setupPage( $term );
150
151 if ( $this->getConfig()->get( 'DisableTextSearch' ) ) {
152 $searchForwardUrl = $this->getConfig()->get( 'SearchForwardUrl' );
153 if ( $searchForwardUrl ) {
154 $url = str_replace( '$1', urlencode( $term ), $searchForwardUrl );
155 $out->redirect( $url );
156 } else {
157 $out->addHTML(
158 "<fieldset>" .
159 "<legend>" .
160 $this->msg( 'search-external' )->escaped() .
161 "</legend>" .
162 "<p class='mw-searchdisabled'>" .
163 $this->msg( 'searchdisabled' )->escaped() .
164 "</p>" .
165 $this->msg( 'googlesearch' )->rawParams(
166 htmlspecialchars( $term ),
167 'UTF-8',
168 $this->msg( 'searchbutton' )->escaped()
169 )->text() .
170 "</fieldset>"
171 );
172 }
173
174 return;
175 }
176
177 $this->showResults( $term );
178 }
179
180 /**
181 * Set up basic search parameters from the request and user settings.
182 *
183 * @see tests/phpunit/includes/specials/SpecialSearchTest.php
184 */
185 public function load() {
186 $request = $this->getRequest();
187 list( $this->limit, $this->offset ) = $request->getLimitOffset( 20, '' );
188 $this->mPrefix = $request->getVal( 'prefix', '' );
189
190 $user = $this->getUser();
191
192 # Extract manually requested namespaces
193 $nslist = $this->powerSearch( $request );
194 if ( !count( $nslist ) ) {
195 # Fallback to user preference
196 $nslist = $this->searchConfig->userNamespaces( $user );
197 }
198
199 $profile = null;
200 if ( !count( $nslist ) ) {
201 $profile = 'default';
202 }
203
204 $profile = $request->getVal( 'profile', $profile );
205 $profiles = $this->getSearchProfiles();
206 if ( $profile === null ) {
207 // BC with old request format
208 $profile = 'advanced';
209 foreach ( $profiles as $key => $data ) {
210 if ( $nslist === $data['namespaces'] && $key !== 'advanced' ) {
211 $profile = $key;
212 }
213 }
214 $this->namespaces = $nslist;
215 } elseif ( $profile === 'advanced' ) {
216 $this->namespaces = $nslist;
217 } else {
218 if ( isset( $profiles[$profile]['namespaces'] ) ) {
219 $this->namespaces = $profiles[$profile]['namespaces'];
220 } else {
221 // Unknown profile requested
222 $profile = 'default';
223 $this->namespaces = $profiles['default']['namespaces'];
224 }
225 }
226
227 $this->fulltext = $request->getVal( 'fulltext' );
228 $this->runSuggestion = (bool)$request->getVal( 'runsuggestion', true );
229 $this->profile = $profile;
230 }
231
232 /**
233 * If an exact title match can be found, jump straight ahead to it.
234 *
235 * @param string $term
236 * @return string|null The url to redirect to, or null if no redirect.
237 */
238 public function goResult( $term ) {
239 # If the string cannot be used to create a title
240 if ( is_null( Title::newFromText( $term ) ) ) {
241 return null;
242 }
243 # If there's an exact or very near match, jump right there.
244 $title = $this->getSearchEngine()
245 ->getNearMatcher( $this->getConfig() )->getNearMatch( $term );
246 if ( is_null( $title ) ) {
247 return null;
248 }
249 $url = null;
250 if ( !Hooks::run( 'SpecialSearchGoResult', [ $term, $title, &$url ] ) ) {
251 return null;
252 }
253
254 return $url === null ? $title->getFullURL() : $url;
255 }
256
257 /**
258 * @param string $term
259 */
260 public function showResults( $term ) {
261 global $wgContLang;
262
263 if ( $this->searchEngineType !== null ) {
264 $this->setExtraParam( 'srbackend', $this->searchEngineType );
265 }
266
267 $out = $this->getOutput();
268 $formWidget = new MediaWiki\Widget\Search\SearchFormWidget(
269 $this,
270 $this->searchConfig,
271 $this->getSearchProfiles()
272 );
273 $filePrefix = $wgContLang->getFormattedNsText( NS_FILE ) . ':';
274 if ( trim( $term ) === '' || $filePrefix === trim( $term ) ) {
275 // Empty query -- straight view of search form
276 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
277 # Hook requested termination
278 return;
279 }
280 $out->enableOOUI();
281 // The form also contains the 'Showing results 0 - 20 of 1234' so we can
282 // only do the form render here for the empty $term case. Rendering
283 // the form when a search is provided is repeated below.
284 $out->addHTML( $formWidget->render(
285 $this->profile, $term, 0, 0, $this->offset, $this->isPowerSearch()
286 ) );
287 return;
288 }
289
290 $search = $this->getSearchEngine();
291 $search->setFeatureData( 'rewrite', $this->runSuggestion );
292 $search->setLimitOffset( $this->limit, $this->offset );
293 $search->setNamespaces( $this->namespaces );
294 $search->prefix = $this->mPrefix;
295 $term = $search->transformSearchTerm( $term );
296
297 Hooks::run( 'SpecialSearchSetupEngine', [ $this, $this->profile, $search ] );
298 if ( !Hooks::run( 'SpecialSearchResultsPrepend', [ $this, $out, $term ] ) ) {
299 # Hook requested termination
300 return;
301 }
302
303 $title = Title::newFromText( $term );
304 $showSuggestion = $title === null || !$title->isKnown();
305 $search->setShowSuggestion( $showSuggestion );
306
307 // fetch search results
308 $rewritten = $search->replacePrefixes( $term );
309
310 $titleMatches = $search->searchTitle( $rewritten );
311 $textMatches = $search->searchText( $rewritten );
312
313 $textStatus = null;
314 if ( $textMatches instanceof Status ) {
315 $textStatus = $textMatches;
316 $textMatches = $textStatus->getValue();
317 }
318
319 // Get number of results
320 $titleMatchesNum = $textMatchesNum = $numTitleMatches = $numTextMatches = 0;
321 if ( $titleMatches ) {
322 $titleMatchesNum = $titleMatches->numRows();
323 $numTitleMatches = $titleMatches->getTotalHits();
324 }
325 if ( $textMatches ) {
326 $textMatchesNum = $textMatches->numRows();
327 $numTextMatches = $textMatches->getTotalHits();
328 if ( $textMatchesNum > 0 ) {
329 $search->augmentSearchResults( $textMatches );
330 }
331 }
332 $num = $titleMatchesNum + $textMatchesNum;
333 $totalRes = $numTitleMatches + $numTextMatches;
334
335 // start rendering the page
336 $out->enableOOUI();
337 $out->addHTML( $formWidget->render(
338 $this->profile, $term, $num, $totalRes, $this->offset, $this->isPowerSearch()
339 ) );
340
341 // did you mean... suggestions
342 if ( $textMatches ) {
343 $dymWidget = new MediaWiki\Widget\Search\DidYouMeanWidget( $this );
344 $out->addHTML( $dymWidget->render( $term, $textMatches ) );
345 }
346
347 $out->addHTML( "<div class='searchresults'>" );
348
349 $hasErrors = $textStatus && $textStatus->getErrors();
350 $hasOtherResults = $textMatches &&
351 $textMatches->hasInterwikiResults( SearchResultSet::INLINE_RESULTS );
352
353 if ( $hasErrors ) {
354 list( $error, $warning ) = $textStatus->splitByErrorType();
355 if ( $error->getErrors() ) {
356 $out->addHTML( Html::rawElement(
357 'div',
358 [ 'class' => 'errorbox' ],
359 $error->getHTML( 'search-error' )
360 ) );
361 }
362 if ( $warning->getErrors() ) {
363 $out->addHTML( Html::rawElement(
364 'div',
365 [ 'class' => 'warningbox' ],
366 $warning->getHTML( 'search-warning' )
367 ) );
368 }
369 }
370
371 // Show the create link ahead
372 $this->showCreateLink( $title, $num, $titleMatches, $textMatches );
373
374 Hooks::run( 'SpecialSearchResults', [ $term, &$titleMatches, &$textMatches ] );
375
376 // If we have no results and have not already displayed an error message
377 if ( $num === 0 && !$hasErrors ) {
378 $out->wrapWikiMsg( "<p class=\"mw-search-nonefound\">\n$1</p>", [
379 $hasOtherResults ? 'search-nonefound-thiswiki' : 'search-nonefound',
380 wfEscapeWikiText( $term )
381 ] );
382 }
383
384 // Although $num might be 0 there can still be secondary or inline
385 // results to display.
386 $linkRenderer = $this->getLinkRenderer();
387 $mainResultWidget = new FullSearchResultWidget( $this, $linkRenderer );
388 $sidebarResultWidget = new SimpleSearchResultWidget( $this, $linkRenderer );
389 $sidebarResultsWidget = new InterwikiSearchResultSetWidget(
390 $this,
391 $sidebarResultWidget,
392 $linkRenderer,
393 MediaWikiServices::getInstance()->getInterwikiLookup()
394 );
395 $widget = new BasicSearchResultSetWidget( $this, $mainResultWidget, $sidebarResultsWidget );
396
397 $out->addHTML( $widget->render(
398 $term, $this->offset, $titleMatches, $textMatches
399 ) );
400
401 if ( $titleMatches ) {
402 $titleMatches->free();
403 }
404
405 if ( $textMatches ) {
406 $textMatches->free();
407 }
408
409 $out->addHTML( '<div class="mw-search-visualclear"></div>' );
410
411 // prev/next links
412 if ( $totalRes > $this->limit || $this->offset ) {
413 $prevnext = $this->getLanguage()->viewPrevNext(
414 $this->getPageTitle(),
415 $this->offset,
416 $this->limit,
417 $this->powerSearchOptions() + [ 'search' => $term ],
418 $this->limit + $this->offset >= $totalRes
419 );
420 $out->addHTML( "<p class='mw-search-pager-bottom'>{$prevnext}</p>\n" );
421 }
422
423 // Close <div class='searchresults'>
424 $out->addHTML( "</div>" );
425
426 Hooks::run( 'SpecialSearchResultsAppend', [ $this, $out, $term ] );
427 }
428
429 /**
430 * @param Title $title
431 * @param int $num The number of search results found
432 * @param null|SearchResultSet $titleMatches Results from title search
433 * @param null|SearchResultSet $textMatches Results from text search
434 */
435 protected function showCreateLink( $title, $num, $titleMatches, $textMatches ) {
436 // show direct page/create link if applicable
437
438 // Check DBkey !== '' in case of fragment link only.
439 if ( is_null( $title ) || $title->getDBkey() === ''
440 || ( $titleMatches !== null && $titleMatches->searchContainedSyntax() )
441 || ( $textMatches !== null && $textMatches->searchContainedSyntax() )
442 ) {
443 // invalid title
444 // preserve the paragraph for margins etc...
445 $this->getOutput()->addHTML( '<p></p>' );
446
447 return;
448 }
449
450 $messageName = 'searchmenu-new-nocreate';
451 $linkClass = 'mw-search-createlink';
452
453 if ( !$title->isExternal() ) {
454 if ( $title->isKnown() ) {
455 $messageName = 'searchmenu-exists';
456 $linkClass = 'mw-search-exists';
457 } elseif ( $title->quickUserCan( 'create', $this->getUser() ) ) {
458 $messageName = 'searchmenu-new';
459 }
460 }
461
462 $params = [
463 $messageName,
464 wfEscapeWikiText( $title->getPrefixedText() ),
465 Message::numParam( $num )
466 ];
467 Hooks::run( 'SpecialSearchCreateLink', [ $title, &$params ] );
468
469 // Extensions using the hook might still return an empty $messageName
470 if ( $messageName ) {
471 $this->getOutput()->wrapWikiMsg( "<p class=\"$linkClass\">\n$1</p>", $params );
472 } else {
473 // preserve the paragraph for margins etc...
474 $this->getOutput()->addHTML( '<p></p>' );
475 }
476 }
477
478 /**
479 * Sets up everything for the HTML output page including styles, javascript,
480 * page title, etc.
481 *
482 * @param string $term
483 */
484 protected function setupPage( $term ) {
485 $out = $this->getOutput();
486
487 $this->setHeaders();
488 $this->outputHeader();
489 // TODO: Is this true? The namespace remember uses a user token
490 // on save.
491 $out->allowClickjacking();
492 $this->addHelpLink( 'Help:Searching' );
493
494 if ( strval( $term ) !== '' ) {
495 $out->setPageTitle( $this->msg( 'searchresults' ) );
496 $out->setHTMLTitle( $this->msg( 'pagetitle' )
497 ->rawParams( $this->msg( 'searchresults-title' )->rawParams( $term )->text() )
498 ->inContentLanguage()->text()
499 );
500 }
501
502 $out->addJsConfigVars( [ 'searchTerm' => $term ] );
503 $out->addModules( 'mediawiki.special.search' );
504 $out->addModuleStyles( [
505 'mediawiki.special', 'mediawiki.special.search.styles', 'mediawiki.ui', 'mediawiki.ui.button',
506 'mediawiki.ui.input', 'mediawiki.widgets.SearchInputWidget.styles',
507 ] );
508 }
509
510 /**
511 * Return true if current search is a power (advanced) search
512 *
513 * @return bool
514 */
515 protected function isPowerSearch() {
516 return $this->profile === 'advanced';
517 }
518
519 /**
520 * Extract "power search" namespace settings from the request object,
521 * returning a list of index numbers to search.
522 *
523 * @param WebRequest $request
524 * @return array
525 */
526 protected function powerSearch( &$request ) {
527 $arr = [];
528 foreach ( $this->searchConfig->searchableNamespaces() as $ns => $name ) {
529 if ( $request->getCheck( 'ns' . $ns ) ) {
530 $arr[] = $ns;
531 }
532 }
533
534 return $arr;
535 }
536
537 /**
538 * Reconstruct the 'power search' options for links
539 * TODO: Instead of exposing this publicly, could we instead expose
540 * a function for creating search links?
541 *
542 * @return array
543 */
544 public function powerSearchOptions() {
545 $opt = [];
546 if ( $this->isPowerSearch() ) {
547 foreach ( $this->namespaces as $n ) {
548 $opt['ns' . $n] = 1;
549 }
550 } else {
551 $opt['profile'] = $this->profile;
552 }
553
554 return $opt + $this->extraParams;
555 }
556
557 /**
558 * Save namespace preferences when we're supposed to
559 *
560 * @return bool Whether we wrote something
561 */
562 protected function saveNamespaces() {
563 $user = $this->getUser();
564 $request = $this->getRequest();
565
566 if ( $user->isLoggedIn() &&
567 $user->matchEditToken(
568 $request->getVal( 'nsRemember' ),
569 'searchnamespace',
570 $request
571 ) && !wfReadOnly()
572 ) {
573 // Reset namespace preferences: namespaces are not searched
574 // when they're not mentioned in the URL parameters.
575 foreach ( MWNamespace::getValidNamespaces() as $n ) {
576 $user->setOption( 'searchNs' . $n, false );
577 }
578 // The request parameters include all the namespaces to be searched.
579 // Even if they're the same as an existing profile, they're not eaten.
580 foreach ( $this->namespaces as $n ) {
581 $user->setOption( 'searchNs' . $n, true );
582 }
583
584 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
585 $user->saveSettings();
586 } );
587
588 return true;
589 }
590
591 return false;
592 }
593
594 /**
595 * @return array
596 */
597 protected function getSearchProfiles() {
598 // Builds list of Search Types (profiles)
599 $nsAllSet = array_keys( $this->searchConfig->searchableNamespaces() );
600 $defaultNs = $this->searchConfig->defaultNamespaces();
601 $profiles = [
602 'default' => [
603 'message' => 'searchprofile-articles',
604 'tooltip' => 'searchprofile-articles-tooltip',
605 'namespaces' => $defaultNs,
606 'namespace-messages' => $this->searchConfig->namespacesAsText(
607 $defaultNs
608 ),
609 ],
610 'images' => [
611 'message' => 'searchprofile-images',
612 'tooltip' => 'searchprofile-images-tooltip',
613 'namespaces' => [ NS_FILE ],
614 ],
615 'all' => [
616 'message' => 'searchprofile-everything',
617 'tooltip' => 'searchprofile-everything-tooltip',
618 'namespaces' => $nsAllSet,
619 ],
620 'advanced' => [
621 'message' => 'searchprofile-advanced',
622 'tooltip' => 'searchprofile-advanced-tooltip',
623 'namespaces' => self::NAMESPACES_CURRENT,
624 ]
625 ];
626
627 Hooks::run( 'SpecialSearchProfiles', [ &$profiles ] );
628
629 foreach ( $profiles as &$data ) {
630 if ( !is_array( $data['namespaces'] ) ) {
631 continue;
632 }
633 sort( $data['namespaces'] );
634 }
635
636 return $profiles;
637 }
638
639 /**
640 * @since 1.18
641 *
642 * @return SearchEngine
643 */
644 public function getSearchEngine() {
645 if ( $this->searchEngine === null ) {
646 $this->searchEngine = $this->searchEngineType ?
647 MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $this->searchEngineType ) :
648 MediaWikiServices::getInstance()->newSearchEngine();
649 }
650
651 return $this->searchEngine;
652 }
653
654 /**
655 * Current search profile.
656 * @return null|string
657 */
658 function getProfile() {
659 return $this->profile;
660 }
661
662 /**
663 * Current namespaces.
664 * @return array
665 */
666 function getNamespaces() {
667 return $this->namespaces;
668 }
669
670 /**
671 * Users of hook SpecialSearchSetupEngine can use this to
672 * add more params to links to not lose selection when
673 * user navigates search results.
674 * @since 1.18
675 *
676 * @param string $key
677 * @param mixed $value
678 */
679 public function setExtraParam( $key, $value ) {
680 $this->extraParams[$key] = $value;
681 }
682
683 protected function getGroupName() {
684 return 'pages';
685 }
686 }