3 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
23 use MediaWiki\MediaWikiServices
;
26 * Query module to perform full text search within wiki titles and content
30 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
33 /** @var array list of api allowed params */
34 private $allowedParams;
36 public function __construct( ApiQuery
$query, $moduleName ) {
37 parent
::__construct( $query, $moduleName, 'sr' );
40 public function execute() {
44 public function executeGenerator( $resultPageSet ) {
45 $this->run( $resultPageSet );
49 * @param ApiPageSet $resultPageSet
52 private function run( $resultPageSet = null ) {
53 $params = $this->extractRequestParams();
56 $query = $params['search'];
57 $what = $params['what'];
58 $interwiki = $params['interwiki'];
59 $searchInfo = array_flip( $params['info'] );
60 $prop = array_flip( $params['prop'] );
62 // Create search engine instance and set options
63 $search = $this->buildSearchEngine( $params );
64 if ( isset( $params['sort'] ) ) {
65 $search->setSort( $params['sort'] );
67 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
68 $search->setFeatureData( 'interwiki', (bool)$interwiki );
70 $nquery = $search->transformSearchTerm( $query );
71 if ( $nquery !== $query ) {
73 wfDeprecated( 'SearchEngine::transformSearchTerm() (overridden by ' .
74 get_class( $search ) . ')', '1.32' );
77 $nquery = $search->replacePrefixes( $query );
78 if ( $nquery !== $query ) {
80 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
81 get_class( $search ) . ')', '1.32' );
83 // Perform the actual search
84 if ( $what == 'text' ) {
85 $matches = $search->searchText( $query );
86 } elseif ( $what == 'title' ) {
87 $matches = $search->searchTitle( $query );
88 } elseif ( $what == 'nearmatch' ) {
89 // near matches must receive the user input as provided, otherwise
90 // the near matches within namespaces are lost.
91 $matches = $search->getNearMatcher( $this->getConfig() )
92 ->getNearMatchResultSet( $params['search'] );
94 // We default to title searches; this is a terrible legacy
95 // of the way we initially set up the MySQL fulltext-based
96 // search engine with separate title and text fields.
97 // In the future, the default should be for a combined index.
99 $matches = $search->searchTitle( $query );
101 // Not all search engines support a separate title search,
102 // for instance the Lucene-based engine we use on Wikipedia.
103 // In this case, fall back to full-text search (which will
104 // include titles in it!)
105 if ( is_null( $matches ) ) {
107 $matches = $search->searchText( $query );
111 if ( $matches instanceof Status
) {
113 $matches = $status->getValue();
119 if ( $status->isOK() ) {
120 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
121 $this->getModuleName(),
125 $this->dieStatus( $status );
127 } elseif ( is_null( $matches ) ) {
128 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
131 if ( $resultPageSet === null ) {
132 $apiResult = $this->getResult();
133 // Add search meta data to result
134 if ( isset( $searchInfo['totalhits'] ) ) {
135 $totalhits = $matches->getTotalHits();
136 if ( $totalhits !== null ) {
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'totalhits', $totalhits );
141 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
142 $apiResult->addValue( [ 'query', 'searchinfo' ],
143 'suggestion', $matches->getSuggestionQuery() );
144 $apiResult->addValue( [ 'query', 'searchinfo' ],
145 'suggestionsnippet', $matches->getSuggestionSnippet() );
147 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
148 $apiResult->addValue( [ 'query', 'searchinfo' ],
149 'rewrittenquery', $matches->getQueryAfterRewrite() );
150 $apiResult->addValue( [ 'query', 'searchinfo' ],
151 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
155 // Add the search results to the result
156 $terms = MediaWikiServices
::getInstance()->getContentLanguage()->
157 convertForSearchResult( $matches->termMatches() );
160 $limit = $params['limit'];
162 if ( $matches->hasMoreResults() ) {
163 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
166 foreach ( $matches as $result ) {
168 // Silently skip broken and missing titles
169 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
173 if ( $resultPageSet === null ) {
174 $vals = $this->getSearchResultData( $result, $prop, $terms );
176 // Add item to results and see whether it fits
177 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
179 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
184 $titles[] = $result->getTitle();
188 // Here we assume interwiki results do not count with
189 // regular search results. We may want to reconsider this
190 // if we ever return a lot of interwiki results or want pagination
192 // Interwiki results inside main result set
193 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
194 if ( $canAddInterwiki ) {
195 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
196 SearchResultSet
::INLINE_RESULTS
);
199 // Interwiki results outside main result set
200 if ( $interwiki && $resultPageSet === null ) {
201 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
202 SearchResultSet
::SECONDARY_RESULTS
);
205 if ( $resultPageSet === null ) {
206 $apiResult->addIndexedTagName( [
207 'query', $this->getModuleName()
210 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
211 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
212 $current['index'] = $new['index'];
216 $resultPageSet->populateFromTitles( $titles );
217 $offset = $params['offset'] +
1;
218 foreach ( $titles as $index => $title ) {
219 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
225 * Assemble search result data.
226 * @param SearchResult $result Search result
227 * @param array $prop Props to extract (as keys)
228 * @param array $terms Terms list
229 * @return array|null Result data or null if result is broken in some way.
231 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
232 // Silently skip broken and missing titles
233 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
239 $title = $result->getTitle();
240 ApiQueryBase
::addTitleInfo( $vals, $title );
241 $vals['pageid'] = $title->getArticleID();
243 if ( isset( $prop['size'] ) ) {
244 $vals['size'] = $result->getByteSize();
246 if ( isset( $prop['wordcount'] ) ) {
247 $vals['wordcount'] = $result->getWordCount();
249 if ( isset( $prop['snippet'] ) ) {
250 $vals['snippet'] = $result->getTextSnippet( $terms );
252 if ( isset( $prop['timestamp'] ) ) {
253 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
255 if ( isset( $prop['titlesnippet'] ) ) {
256 $vals['titlesnippet'] = $result->getTitleSnippet();
258 if ( isset( $prop['categorysnippet'] ) ) {
259 $vals['categorysnippet'] = $result->getCategorySnippet();
261 if ( !is_null( $result->getRedirectTitle() ) ) {
262 if ( isset( $prop['redirecttitle'] ) ) {
263 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
265 if ( isset( $prop['redirectsnippet'] ) ) {
266 $vals['redirectsnippet'] = $result->getRedirectSnippet();
269 if ( !is_null( $result->getSectionTitle() ) ) {
270 if ( isset( $prop['sectiontitle'] ) ) {
271 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
273 if ( isset( $prop['sectionsnippet'] ) ) {
274 $vals['sectionsnippet'] = $result->getSectionSnippet();
277 if ( isset( $prop['isfilematch'] ) ) {
278 $vals['isfilematch'] = $result->isFileMatch();
281 if ( isset( $prop['extensiondata'] ) ) {
282 $extra = $result->getExtensionData();
283 // Add augmented data to the result. The data would be organized as a map:
284 // augmentorName => data
286 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
294 * Add interwiki results as a section in query results.
295 * @param SearchResultSet $matches
296 * @param ApiResult $apiResult
297 * @param array $prop Props to extract (as keys)
298 * @param array $terms Terms list
299 * @param string $section Section name where results would go
300 * @param int $type Interwiki result type
301 * @return int|null Number of total hits in the data or null if none was produced
303 private function addInterwikiResults(
304 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
305 $terms, $section, $type
308 if ( $matches->hasInterwikiResults( $type ) ) {
309 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
310 // Include number of results if requested
311 $totalhits +
= $interwikiMatches->getTotalHits();
313 foreach ( $interwikiMatches as $result ) {
314 $title = $result->getTitle();
315 $vals = $this->getSearchResultData( $result, $prop, $terms );
317 $vals['namespace'] = $result->getInterwikiNamespaceText();
318 $vals['title'] = $title->getText();
319 $vals['url'] = $title->getFullURL();
321 // Add item to results and see whether it fits
322 $fit = $apiResult->addValue( [
324 $section . $this->getModuleName(),
325 $result->getInterwikiPrefix()
329 // We hit the limit. We can't really provide any meaningful
330 // pagination info so just bail out
335 if ( $totalhits !== null ) {
336 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
337 $apiResult->addIndexedTagName( [
338 'query', $section . $this->getModuleName()
345 public function getCacheMode( $params ) {
349 public function getAllowedParams() {
350 if ( $this->allowedParams
!== null ) {
351 return $this->allowedParams
;
354 $this->allowedParams
= $this->buildCommonApiParams() +
[
356 ApiBase
::PARAM_TYPE
=> [
363 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
364 ApiBase
::PARAM_TYPE
=> [
369 ApiBase
::PARAM_ISMULTI
=> true,
372 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
373 ApiBase
::PARAM_TYPE
=> [
385 'score', // deprecated
386 'hasrelated', // deprecated
389 ApiBase
::PARAM_ISMULTI
=> true,
390 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
391 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
396 'interwiki' => false,
397 'enablerewrites' => false,
400 // If we have more than one engine the list of available sorts is
401 // difficult to represent. For now don't expose it.
402 $alternatives = MediaWiki\MediaWikiServices
::getInstance()
403 ->getSearchEngineConfig()
405 if ( count( $alternatives ) == 1 ) {
406 $this->allowedParams
['sort'] = [
407 ApiBase
::PARAM_DFLT
=> 'relevance',
408 ApiBase
::PARAM_TYPE
=> MediaWiki\MediaWikiServices
::getInstance()
414 return $this->allowedParams
;
417 public function getSearchProfileParams() {
420 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
421 'help-message' => 'apihelp-query+search-param-qiprofile',
426 protected function getExamplesMessages() {
428 'action=query&list=search&srsearch=meaning'
429 => 'apihelp-query+search-example-simple',
430 'action=query&list=search&srwhat=text&srsearch=meaning'
431 => 'apihelp-query+search-example-text',
432 'action=query&generator=search&gsrsearch=meaning&prop=info'
433 => 'apihelp-query+search-example-generator',
437 public function getHelpUrls() {
438 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';