ApiQuerySearch.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. /**
  23. * Query module to perform full text search within wiki titles and content
  24. *
  25. * @ingroup API
  26. */
  27. class ApiQuerySearch extends ApiQueryGeneratorBase {
  28. use SearchApi;
  29. /** @var array list of api allowed params */
  30. private $allowedParams;
  31. public function __construct( ApiQuery $query, $moduleName ) {
  32. parent::__construct( $query, $moduleName, 'sr' );
  33. }
  34. public function execute() {
  35. $this->run();
  36. }
  37. public function executeGenerator( $resultPageSet ) {
  38. $this->run( $resultPageSet );
  39. }
  40. /**
  41. * @param ApiPageSet $resultPageSet
  42. * @return void
  43. */
  44. private function run( $resultPageSet = null ) {
  45. $params = $this->extractRequestParams();
  46. // Extract parameters
  47. $query = $params['search'];
  48. $what = $params['what'];
  49. $interwiki = $params['interwiki'];
  50. $searchInfo = array_flip( $params['info'] );
  51. $prop = array_flip( $params['prop'] );
  52. // Create search engine instance and set options
  53. $search = $this->buildSearchEngine( $params );
  54. if ( isset( $params['sort'] ) ) {
  55. $search->setSort( $params['sort'] );
  56. }
  57. $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
  58. $search->setFeatureData( 'interwiki', (bool)$interwiki );
  59. $nquery = $search->replacePrefixes( $query );
  60. if ( $nquery !== $query ) {
  61. $query = $nquery;
  62. wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
  63. get_class( $search ) . ')', '1.32' );
  64. }
  65. // Perform the actual search
  66. if ( $what == 'text' ) {
  67. $matches = $search->searchText( $query );
  68. } elseif ( $what == 'title' ) {
  69. $matches = $search->searchTitle( $query );
  70. } elseif ( $what == 'nearmatch' ) {
  71. // near matches must receive the user input as provided, otherwise
  72. // the near matches within namespaces are lost.
  73. $matches = $search->getNearMatcher( $this->getConfig() )
  74. ->getNearMatchResultSet( $params['search'] );
  75. } else {
  76. // We default to title searches; this is a terrible legacy
  77. // of the way we initially set up the MySQL fulltext-based
  78. // search engine with separate title and text fields.
  79. // In the future, the default should be for a combined index.
  80. $what = 'title';
  81. $matches = $search->searchTitle( $query );
  82. // Not all search engines support a separate title search,
  83. // for instance the Lucene-based engine we use on Wikipedia.
  84. // In this case, fall back to full-text search (which will
  85. // include titles in it!)
  86. if ( is_null( $matches ) ) {
  87. $what = 'text';
  88. $matches = $search->searchText( $query );
  89. }
  90. }
  91. if ( $matches instanceof Status ) {
  92. $status = $matches;
  93. $matches = $status->getValue();
  94. } else {
  95. $status = null;
  96. }
  97. if ( $status ) {
  98. if ( $status->isOK() ) {
  99. $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
  100. $this->getModuleName(),
  101. $status
  102. );
  103. } else {
  104. $this->dieStatus( $status );
  105. }
  106. } elseif ( is_null( $matches ) ) {
  107. $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
  108. }
  109. if ( $resultPageSet === null ) {
  110. $apiResult = $this->getResult();
  111. // Add search meta data to result
  112. if ( isset( $searchInfo['totalhits'] ) ) {
  113. $totalhits = $matches->getTotalHits();
  114. if ( $totalhits !== null ) {
  115. $apiResult->addValue( [ 'query', 'searchinfo' ],
  116. 'totalhits', $totalhits );
  117. }
  118. }
  119. if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
  120. $apiResult->addValue( [ 'query', 'searchinfo' ],
  121. 'suggestion', $matches->getSuggestionQuery() );
  122. $apiResult->addValue( [ 'query', 'searchinfo' ],
  123. 'suggestionsnippet', $matches->getSuggestionSnippet() );
  124. }
  125. if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
  126. $apiResult->addValue( [ 'query', 'searchinfo' ],
  127. 'rewrittenquery', $matches->getQueryAfterRewrite() );
  128. $apiResult->addValue( [ 'query', 'searchinfo' ],
  129. 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
  130. }
  131. }
  132. $titles = [];
  133. $count = 0;
  134. if ( $matches->hasMoreResults() ) {
  135. $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
  136. }
  137. foreach ( $matches as $result ) {
  138. $count++;
  139. // Silently skip broken and missing titles
  140. if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
  141. continue;
  142. }
  143. if ( $resultPageSet === null ) {
  144. $vals = $this->getSearchResultData( $result, $prop );
  145. if ( $vals ) {
  146. // Add item to results and see whether it fits
  147. $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
  148. if ( !$fit ) {
  149. $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
  150. break;
  151. }
  152. }
  153. } else {
  154. $titles[] = $result->getTitle();
  155. }
  156. }
  157. // Here we assume interwiki results do not count with
  158. // regular search results. We may want to reconsider this
  159. // if we ever return a lot of interwiki results or want pagination
  160. // for them.
  161. // Interwiki results inside main result set
  162. $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
  163. if ( $canAddInterwiki ) {
  164. $this->addInterwikiResults( $matches, $apiResult, $prop, 'additional',
  165. ISearchResultSet::INLINE_RESULTS );
  166. }
  167. // Interwiki results outside main result set
  168. if ( $interwiki && $resultPageSet === null ) {
  169. $this->addInterwikiResults( $matches, $apiResult, $prop, 'interwiki',
  170. ISearchResultSet::SECONDARY_RESULTS );
  171. }
  172. if ( $resultPageSet === null ) {
  173. $apiResult->addIndexedTagName( [
  174. 'query', $this->getModuleName()
  175. ], 'p' );
  176. } else {
  177. $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
  178. if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
  179. $current['index'] = $new['index'];
  180. }
  181. return $current;
  182. } );
  183. $resultPageSet->populateFromTitles( $titles );
  184. $offset = $params['offset'] + 1;
  185. foreach ( $titles as $index => $title ) {
  186. $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
  187. }
  188. }
  189. }
  190. /**
  191. * Assemble search result data.
  192. * @param SearchResult $result Search result
  193. * @param array $prop Props to extract (as keys)
  194. * @return array|null Result data or null if result is broken in some way.
  195. */
  196. private function getSearchResultData( SearchResult $result, $prop ) {
  197. // Silently skip broken and missing titles
  198. if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
  199. return null;
  200. }
  201. $vals = [];
  202. $title = $result->getTitle();
  203. ApiQueryBase::addTitleInfo( $vals, $title );
  204. $vals['pageid'] = $title->getArticleID();
  205. if ( isset( $prop['size'] ) ) {
  206. $vals['size'] = $result->getByteSize();
  207. }
  208. if ( isset( $prop['wordcount'] ) ) {
  209. $vals['wordcount'] = $result->getWordCount();
  210. }
  211. if ( isset( $prop['snippet'] ) ) {
  212. $vals['snippet'] = $result->getTextSnippet();
  213. }
  214. if ( isset( $prop['timestamp'] ) ) {
  215. $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
  216. }
  217. if ( isset( $prop['titlesnippet'] ) ) {
  218. $vals['titlesnippet'] = $result->getTitleSnippet();
  219. }
  220. if ( isset( $prop['categorysnippet'] ) ) {
  221. $vals['categorysnippet'] = $result->getCategorySnippet();
  222. }
  223. if ( !is_null( $result->getRedirectTitle() ) ) {
  224. if ( isset( $prop['redirecttitle'] ) ) {
  225. $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
  226. }
  227. if ( isset( $prop['redirectsnippet'] ) ) {
  228. $vals['redirectsnippet'] = $result->getRedirectSnippet();
  229. }
  230. }
  231. if ( !is_null( $result->getSectionTitle() ) ) {
  232. if ( isset( $prop['sectiontitle'] ) ) {
  233. $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
  234. }
  235. if ( isset( $prop['sectionsnippet'] ) ) {
  236. $vals['sectionsnippet'] = $result->getSectionSnippet();
  237. }
  238. }
  239. if ( isset( $prop['isfilematch'] ) ) {
  240. $vals['isfilematch'] = $result->isFileMatch();
  241. }
  242. if ( isset( $prop['extensiondata'] ) ) {
  243. $extra = $result->getExtensionData();
  244. // Add augmented data to the result. The data would be organized as a map:
  245. // augmentorName => data
  246. if ( $extra ) {
  247. $vals['extensiondata'] = ApiResult::addMetadataToResultVars( $extra );
  248. }
  249. }
  250. return $vals;
  251. }
  252. /**
  253. * Add interwiki results as a section in query results.
  254. * @param ISearchResultSet $matches
  255. * @param ApiResult $apiResult
  256. * @param array $prop Props to extract (as keys)
  257. * @param string $section Section name where results would go
  258. * @param int $type Interwiki result type
  259. * @return int|null Number of total hits in the data or null if none was produced
  260. */
  261. private function addInterwikiResults(
  262. ISearchResultSet $matches, ApiResult $apiResult, $prop,
  263. $section, $type
  264. ) {
  265. $totalhits = null;
  266. if ( $matches->hasInterwikiResults( $type ) ) {
  267. foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
  268. // Include number of results if requested
  269. $totalhits += $interwikiMatches->getTotalHits();
  270. foreach ( $interwikiMatches as $result ) {
  271. $title = $result->getTitle();
  272. $vals = $this->getSearchResultData( $result, $prop );
  273. $vals['namespace'] = $result->getInterwikiNamespaceText();
  274. $vals['title'] = $title->getText();
  275. $vals['url'] = $title->getFullURL();
  276. // Add item to results and see whether it fits
  277. $fit = $apiResult->addValue( [
  278. 'query',
  279. $section . $this->getModuleName(),
  280. $result->getInterwikiPrefix()
  281. ], null, $vals );
  282. if ( !$fit ) {
  283. // We hit the limit. We can't really provide any meaningful
  284. // pagination info so just bail out
  285. break;
  286. }
  287. }
  288. }
  289. if ( $totalhits !== null ) {
  290. $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
  291. $apiResult->addIndexedTagName( [
  292. 'query', $section . $this->getModuleName()
  293. ], 'p' );
  294. }
  295. }
  296. return $totalhits;
  297. }
  298. public function getCacheMode( $params ) {
  299. return 'public';
  300. }
  301. public function getAllowedParams() {
  302. if ( $this->allowedParams !== null ) {
  303. return $this->allowedParams;
  304. }
  305. $this->allowedParams = $this->buildCommonApiParams() + [
  306. 'what' => [
  307. ApiBase::PARAM_TYPE => [
  308. 'title',
  309. 'text',
  310. 'nearmatch',
  311. ]
  312. ],
  313. 'info' => [
  314. ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
  315. ApiBase::PARAM_TYPE => [
  316. 'totalhits',
  317. 'suggestion',
  318. 'rewrittenquery',
  319. ],
  320. ApiBase::PARAM_ISMULTI => true,
  321. ],
  322. 'prop' => [
  323. ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
  324. ApiBase::PARAM_TYPE => [
  325. 'size',
  326. 'wordcount',
  327. 'timestamp',
  328. 'snippet',
  329. 'titlesnippet',
  330. 'redirecttitle',
  331. 'redirectsnippet',
  332. 'sectiontitle',
  333. 'sectionsnippet',
  334. 'isfilematch',
  335. 'categorysnippet',
  336. 'score', // deprecated
  337. 'hasrelated', // deprecated
  338. 'extensiondata',
  339. ],
  340. ApiBase::PARAM_ISMULTI => true,
  341. ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
  342. ApiBase::PARAM_DEPRECATED_VALUES => [
  343. 'score' => true,
  344. 'hasrelated' => true
  345. ],
  346. ],
  347. 'interwiki' => false,
  348. 'enablerewrites' => false,
  349. ];
  350. // If we have more than one engine the list of available sorts is
  351. // difficult to represent. For now don't expose it.
  352. $services = MediaWiki\MediaWikiServices::getInstance();
  353. $alternatives = $services
  354. ->getSearchEngineConfig()
  355. ->getSearchTypes();
  356. if ( count( $alternatives ) == 1 ) {
  357. $this->allowedParams['sort'] = [
  358. ApiBase::PARAM_DFLT => 'relevance',
  359. ApiBase::PARAM_TYPE => $services
  360. ->newSearchEngine()
  361. ->getValidSorts(),
  362. ];
  363. }
  364. return $this->allowedParams;
  365. }
  366. public function getSearchProfileParams() {
  367. return [
  368. 'qiprofile' => [
  369. 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
  370. 'help-message' => 'apihelp-query+search-param-qiprofile',
  371. ],
  372. ];
  373. }
  374. protected function getExamplesMessages() {
  375. return [
  376. 'action=query&list=search&srsearch=meaning'
  377. => 'apihelp-query+search-example-simple',
  378. 'action=query&list=search&srwhat=text&srsearch=meaning'
  379. => 'apihelp-query+search-example-text',
  380. 'action=query&generator=search&gsrsearch=meaning&prop=info'
  381. => 'apihelp-query+search-example-generator',
  382. ];
  383. }
  384. public function getHelpUrls() {
  385. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';
  386. }
  387. }