SpecialSearch.php 23 KB

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