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 ) {
51 $params = $this->extractRequestParams();
54 $query = $params['search'];
55 $what = $params['what'];
56 $interwiki = $params['interwiki'];
57 $searchInfo = array_flip( $params['info'] );
58 $prop = array_flip( $params['prop'] );
60 // Create search engine instance and set options
61 $search = $this->buildSearchEngine( $params );
62 if ( isset( $params['sort'] ) ) {
63 $search->setSort( $params['sort'] );
65 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
66 $search->setFeatureData( 'interwiki', (bool)$interwiki );
68 $nquery = $search->replacePrefixes( $query );
69 if ( $nquery !== $query ) {
71 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
72 get_class( $search ) . ')', '1.32' );
74 // Perform the actual search
75 if ( $what == 'text' ) {
76 $matches = $search->searchText( $query );
77 } elseif ( $what == 'title' ) {
78 $matches = $search->searchTitle( $query );
79 } elseif ( $what == 'nearmatch' ) {
80 // near matches must receive the user input as provided, otherwise
81 // the near matches within namespaces are lost.
82 $matches = $search->getNearMatcher( $this->getConfig() )
83 ->getNearMatchResultSet( $params['search'] );
85 // We default to title searches; this is a terrible legacy
86 // of the way we initially set up the MySQL fulltext-based
87 // search engine with separate title and text fields.
88 // In the future, the default should be for a combined index.
90 $matches = $search->searchTitle( $query );
92 // Not all search engines support a separate title search,
93 // for instance the Lucene-based engine we use on Wikipedia.
94 // In this case, fall back to full-text search (which will
95 // include titles in it!)
96 if ( is_null( $matches ) ) {
98 $matches = $search->searchText( $query );
102 if ( $matches instanceof Status
) {
104 $matches = $status->getValue();
110 if ( $status->isOK() ) {
111 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
112 $this->getModuleName(),
116 $this->dieStatus( $status );
118 } elseif ( is_null( $matches ) ) {
119 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
122 if ( $resultPageSet === null ) {
123 $apiResult = $this->getResult();
124 // Add search meta data to result
125 if ( isset( $searchInfo['totalhits'] ) ) {
126 $totalhits = $matches->getTotalHits();
127 if ( $totalhits !== null ) {
128 $apiResult->addValue( [ 'query', 'searchinfo' ],
129 'totalhits', $totalhits );
132 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
133 $apiResult->addValue( [ 'query', 'searchinfo' ],
134 'suggestion', $matches->getSuggestionQuery() );
135 $apiResult->addValue( [ 'query', 'searchinfo' ],
136 'suggestionsnippet', $matches->getSuggestionSnippet() );
138 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'rewrittenquery', $matches->getQueryAfterRewrite() );
141 $apiResult->addValue( [ 'query', 'searchinfo' ],
142 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
149 if ( $matches->hasMoreResults() ) {
150 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
153 foreach ( $matches as $result ) {
155 // Silently skip broken and missing titles
156 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
160 if ( $resultPageSet === null ) {
161 $vals = $this->getSearchResultData( $result, $prop );
163 // Add item to results and see whether it fits
164 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
166 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
171 $titles[] = $result->getTitle();
175 // Here we assume interwiki results do not count with
176 // regular search results. We may want to reconsider this
177 // if we ever return a lot of interwiki results or want pagination
179 // Interwiki results inside main result set
180 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
181 if ( $canAddInterwiki ) {
182 $this->addInterwikiResults( $matches, $apiResult, $prop, 'additional',
183 ISearchResultSet
::INLINE_RESULTS
);
186 // Interwiki results outside main result set
187 if ( $interwiki && $resultPageSet === null ) {
188 $this->addInterwikiResults( $matches, $apiResult, $prop, 'interwiki',
189 ISearchResultSet
::SECONDARY_RESULTS
);
192 if ( $resultPageSet === null ) {
193 $apiResult->addIndexedTagName( [
194 'query', $this->getModuleName()
197 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
198 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
199 $current['index'] = $new['index'];
203 $resultPageSet->populateFromTitles( $titles );
204 $offset = $params['offset'] +
1;
205 foreach ( $titles as $index => $title ) {
206 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
212 * Assemble search result data.
213 * @param SearchResult $result Search result
214 * @param array $prop Props to extract (as keys)
215 * @return array|null Result data or null if result is broken in some way.
217 private function getSearchResultData( SearchResult
$result, $prop ) {
218 // Silently skip broken and missing titles
219 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
225 $title = $result->getTitle();
226 ApiQueryBase
::addTitleInfo( $vals, $title );
227 $vals['pageid'] = $title->getArticleID();
229 if ( isset( $prop['size'] ) ) {
230 $vals['size'] = $result->getByteSize();
232 if ( isset( $prop['wordcount'] ) ) {
233 $vals['wordcount'] = $result->getWordCount();
235 if ( isset( $prop['snippet'] ) ) {
236 $vals['snippet'] = $result->getTextSnippet();
238 if ( isset( $prop['timestamp'] ) ) {
239 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
241 if ( isset( $prop['titlesnippet'] ) ) {
242 $vals['titlesnippet'] = $result->getTitleSnippet();
244 if ( isset( $prop['categorysnippet'] ) ) {
245 $vals['categorysnippet'] = $result->getCategorySnippet();
247 if ( !is_null( $result->getRedirectTitle() ) ) {
248 if ( isset( $prop['redirecttitle'] ) ) {
249 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
251 if ( isset( $prop['redirectsnippet'] ) ) {
252 $vals['redirectsnippet'] = $result->getRedirectSnippet();
255 if ( !is_null( $result->getSectionTitle() ) ) {
256 if ( isset( $prop['sectiontitle'] ) ) {
257 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
259 if ( isset( $prop['sectionsnippet'] ) ) {
260 $vals['sectionsnippet'] = $result->getSectionSnippet();
263 if ( isset( $prop['isfilematch'] ) ) {
264 $vals['isfilematch'] = $result->isFileMatch();
267 if ( isset( $prop['extensiondata'] ) ) {
268 $extra = $result->getExtensionData();
269 // Add augmented data to the result. The data would be organized as a map:
270 // augmentorName => data
272 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
280 * Add interwiki results as a section in query results.
281 * @param ISearchResultSet $matches
282 * @param ApiResult $apiResult
283 * @param array $prop Props to extract (as keys)
284 * @param string $section Section name where results would go
285 * @param int $type Interwiki result type
286 * @return int|null Number of total hits in the data or null if none was produced
288 private function addInterwikiResults(
289 ISearchResultSet
$matches, ApiResult
$apiResult, $prop,
293 if ( $matches->hasInterwikiResults( $type ) ) {
294 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
295 // Include number of results if requested
296 $totalhits +
= $interwikiMatches->getTotalHits();
298 foreach ( $interwikiMatches as $result ) {
299 $title = $result->getTitle();
300 $vals = $this->getSearchResultData( $result, $prop );
302 $vals['namespace'] = $result->getInterwikiNamespaceText();
303 $vals['title'] = $title->getText();
304 $vals['url'] = $title->getFullURL();
306 // Add item to results and see whether it fits
307 $fit = $apiResult->addValue( [
309 $section . $this->getModuleName(),
310 $result->getInterwikiPrefix()
314 // We hit the limit. We can't really provide any meaningful
315 // pagination info so just bail out
320 if ( $totalhits !== null ) {
321 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
322 $apiResult->addIndexedTagName( [
323 'query', $section . $this->getModuleName()
330 public function getCacheMode( $params ) {
334 public function getAllowedParams() {
335 if ( $this->allowedParams
!== null ) {
336 return $this->allowedParams
;
339 $this->allowedParams
= $this->buildCommonApiParams() +
[
341 ApiBase
::PARAM_TYPE
=> [
348 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
349 ApiBase
::PARAM_TYPE
=> [
354 ApiBase
::PARAM_ISMULTI
=> true,
357 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
358 ApiBase
::PARAM_TYPE
=> [
370 'score', // deprecated
371 'hasrelated', // deprecated
374 ApiBase
::PARAM_ISMULTI
=> true,
375 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
376 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
381 'interwiki' => false,
382 'enablerewrites' => false,
385 // If we have more than one engine the list of available sorts is
386 // difficult to represent. For now don't expose it.
387 $services = MediaWiki\MediaWikiServices
::getInstance();
388 $alternatives = $services
389 ->getSearchEngineConfig()
391 if ( count( $alternatives ) == 1 ) {
392 $this->allowedParams
['sort'] = [
393 ApiBase
::PARAM_DFLT
=> 'relevance',
394 ApiBase
::PARAM_TYPE
=> $services
400 return $this->allowedParams
;
403 public function getSearchProfileParams() {
406 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
407 'help-message' => 'apihelp-query+search-param-qiprofile',
412 protected function getExamplesMessages() {
414 'action=query&list=search&srsearch=meaning'
415 => 'apihelp-query+search-example-simple',
416 'action=query&list=search&srwhat=text&srsearch=meaning'
417 => 'apihelp-query+search-example-text',
418 'action=query&generator=search&gsrsearch=meaning&prop=info'
419 => 'apihelp-query+search-example-generator',
423 public function getHelpUrls() {
424 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';