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
24 * Query module to perform full text search within wiki titles and content
28 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
31 /** @var array list of api allowed params */
32 private $allowedParams;
34 public function __construct( ApiQuery
$query, $moduleName ) {
35 parent
::__construct( $query, $moduleName, 'sr' );
38 public function execute() {
42 public function executeGenerator( $resultPageSet ) {
43 $this->run( $resultPageSet );
47 * @param ApiPageSet $resultPageSet
50 private function run( $resultPageSet = null ) {
52 $params = $this->extractRequestParams();
55 $query = $params['search'];
56 $what = $params['what'];
57 $interwiki = $params['interwiki'];
58 $searchInfo = array_flip( $params['info'] );
59 $prop = array_flip( $params['prop'] );
61 // Create search engine instance and set options
62 $search = $this->buildSearchEngine( $params );
63 if ( isset( $params['sort'] ) ) {
64 $search->setSort( $params['sort'] );
66 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
67 $search->setFeatureData( 'interwiki', (bool)$interwiki );
69 $query = $search->transformSearchTerm( $query );
70 $query = $search->replacePrefixes( $query );
72 // Perform the actual search
73 if ( $what == 'text' ) {
74 $matches = $search->searchText( $query );
75 } elseif ( $what == 'title' ) {
76 $matches = $search->searchTitle( $query );
77 } elseif ( $what == 'nearmatch' ) {
78 // near matches must receive the user input as provided, otherwise
79 // the near matches within namespaces are lost.
80 $matches = $search->getNearMatcher( $this->getConfig() )
81 ->getNearMatchResultSet( $params['search'] );
83 // We default to title searches; this is a terrible legacy
84 // of the way we initially set up the MySQL fulltext-based
85 // search engine with separate title and text fields.
86 // In the future, the default should be for a combined index.
88 $matches = $search->searchTitle( $query );
90 // Not all search engines support a separate title search,
91 // for instance the Lucene-based engine we use on Wikipedia.
92 // In this case, fall back to full-text search (which will
93 // include titles in it!)
94 if ( is_null( $matches ) ) {
96 $matches = $search->searchText( $query );
100 if ( $matches instanceof Status
) {
102 $matches = $status->getValue();
108 if ( $status->isOK() ) {
109 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
110 $this->getModuleName(),
114 $this->dieStatus( $status );
116 } elseif ( is_null( $matches ) ) {
117 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
120 if ( $resultPageSet === null ) {
121 $apiResult = $this->getResult();
122 // Add search meta data to result
123 if ( isset( $searchInfo['totalhits'] ) ) {
124 $totalhits = $matches->getTotalHits();
125 if ( $totalhits !== null ) {
126 $apiResult->addValue( [ 'query', 'searchinfo' ],
127 'totalhits', $totalhits );
130 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
131 $apiResult->addValue( [ 'query', 'searchinfo' ],
132 'suggestion', $matches->getSuggestionQuery() );
133 $apiResult->addValue( [ 'query', 'searchinfo' ],
134 'suggestionsnippet', $matches->getSuggestionSnippet() );
136 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'rewrittenquery', $matches->getQueryAfterRewrite() );
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
144 // Add the search results to the result
145 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
148 $limit = $params['limit'];
150 if ( $matches->hasMoreResults() ) {
151 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
154 foreach ( $matches as $result ) {
156 // Silently skip broken and missing titles
157 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
161 if ( $resultPageSet === null ) {
162 $vals = $this->getSearchResultData( $result, $prop, $terms );
164 // Add item to results and see whether it fits
165 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
167 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
172 $titles[] = $result->getTitle();
176 // Here we assume interwiki results do not count with
177 // regular search results. We may want to reconsider this
178 // if we ever return a lot of interwiki results or want pagination
180 // Interwiki results inside main result set
181 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
182 if ( $canAddInterwiki ) {
183 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
184 SearchResultSet
::INLINE_RESULTS
);
187 // Interwiki results outside main result set
188 if ( $interwiki && $resultPageSet === null ) {
189 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
190 SearchResultSet
::SECONDARY_RESULTS
);
193 if ( $resultPageSet === null ) {
194 $apiResult->addIndexedTagName( [
195 'query', $this->getModuleName()
198 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
199 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
200 $current['index'] = $new['index'];
204 $resultPageSet->populateFromTitles( $titles );
205 $offset = $params['offset'] +
1;
206 foreach ( $titles as $index => $title ) {
207 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
213 * Assemble search result data.
214 * @param SearchResult $result Search result
215 * @param array $prop Props to extract (as keys)
216 * @param array $terms Terms list
217 * @return array|null Result data or null if result is broken in some way.
219 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
220 // Silently skip broken and missing titles
221 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
227 $title = $result->getTitle();
228 ApiQueryBase
::addTitleInfo( $vals, $title );
229 $vals['pageid'] = $title->getArticleID();
231 if ( isset( $prop['size'] ) ) {
232 $vals['size'] = $result->getByteSize();
234 if ( isset( $prop['wordcount'] ) ) {
235 $vals['wordcount'] = $result->getWordCount();
237 if ( isset( $prop['snippet'] ) ) {
238 $vals['snippet'] = $result->getTextSnippet( $terms );
240 if ( isset( $prop['timestamp'] ) ) {
241 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
243 if ( isset( $prop['titlesnippet'] ) ) {
244 $vals['titlesnippet'] = $result->getTitleSnippet();
246 if ( isset( $prop['categorysnippet'] ) ) {
247 $vals['categorysnippet'] = $result->getCategorySnippet();
249 if ( !is_null( $result->getRedirectTitle() ) ) {
250 if ( isset( $prop['redirecttitle'] ) ) {
251 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
253 if ( isset( $prop['redirectsnippet'] ) ) {
254 $vals['redirectsnippet'] = $result->getRedirectSnippet();
257 if ( !is_null( $result->getSectionTitle() ) ) {
258 if ( isset( $prop['sectiontitle'] ) ) {
259 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
261 if ( isset( $prop['sectionsnippet'] ) ) {
262 $vals['sectionsnippet'] = $result->getSectionSnippet();
265 if ( isset( $prop['isfilematch'] ) ) {
266 $vals['isfilematch'] = $result->isFileMatch();
269 if ( isset( $prop['extensiondata'] ) ) {
270 $extra = $result->getExtensionData();
271 // Add augmented data to the result. The data would be organized as a map:
272 // augmentorName => data
274 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
282 * Add interwiki results as a section in query results.
283 * @param SearchResultSet $matches
284 * @param ApiResult $apiResult
285 * @param array $prop Props to extract (as keys)
286 * @param array $terms Terms list
287 * @param string $section Section name where results would go
288 * @param int $type Interwiki result type
289 * @return int|null Number of total hits in the data or null if none was produced
291 private function addInterwikiResults(
292 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
293 $terms, $section, $type
296 if ( $matches->hasInterwikiResults( $type ) ) {
297 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
298 // Include number of results if requested
299 $totalhits +
= $interwikiMatches->getTotalHits();
301 foreach ( $interwikiMatches as $result ) {
302 $title = $result->getTitle();
303 $vals = $this->getSearchResultData( $result, $prop, $terms );
305 $vals['namespace'] = $result->getInterwikiNamespaceText();
306 $vals['title'] = $title->getText();
307 $vals['url'] = $title->getFullURL();
309 // Add item to results and see whether it fits
310 $fit = $apiResult->addValue( [
312 $section . $this->getModuleName(),
313 $result->getInterwikiPrefix()
317 // We hit the limit. We can't really provide any meaningful
318 // pagination info so just bail out
323 if ( $totalhits !== null ) {
324 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
325 $apiResult->addIndexedTagName( [
326 'query', $section . $this->getModuleName()
333 public function getCacheMode( $params ) {
337 public function getAllowedParams() {
338 if ( $this->allowedParams
!== null ) {
339 return $this->allowedParams
;
342 $this->allowedParams
= $this->buildCommonApiParams() +
[
344 ApiBase
::PARAM_TYPE
=> [
351 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
352 ApiBase
::PARAM_TYPE
=> [
357 ApiBase
::PARAM_ISMULTI
=> true,
360 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
361 ApiBase
::PARAM_TYPE
=> [
373 'score', // deprecated
374 'hasrelated', // deprecated
377 ApiBase
::PARAM_ISMULTI
=> true,
378 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
379 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
384 'interwiki' => false,
385 'enablerewrites' => false,
388 // If we have more than one engine the list of available sorts is
389 // difficult to represent. For now don't expose it.
390 $alternatives = MediaWiki\MediaWikiServices
::getInstance()
391 ->getSearchEngineConfig()
393 if ( count( $alternatives ) == 1 ) {
394 $this->allowedParams
['sort'] = [
395 ApiBase
::PARAM_DFLT
=> 'relevance',
396 ApiBase
::PARAM_TYPE
=> MediaWiki\MediaWikiServices
::getInstance()
402 return $this->allowedParams
;
405 public function getSearchProfileParams() {
408 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
409 'help-message' => 'apihelp-query+search-param-qiprofile',
414 protected function getExamplesMessages() {
416 'action=query&list=search&srsearch=meaning'
417 => 'apihelp-query+search-example-simple',
418 'action=query&list=search&srwhat=text&srsearch=meaning'
419 => 'apihelp-query+search-example-text',
420 'action=query&generator=search&gsrsearch=meaning&prop=info'
421 => 'apihelp-query+search-example-generator',
425 public function getHelpUrls() {
426 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';