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 $nquery = $search->transformSearchTerm( $query );
70 if ( $nquery !== $query ) {
72 wfDeprecated( 'SearchEngine::transformSearchTerm() (overridden by ' .
73 get_class( $search ) . ')', '1.32' );
75 $query = $search->replacePrefixes( $query );
77 // Perform the actual search
78 if ( $what == 'text' ) {
79 $matches = $search->searchText( $query );
80 } elseif ( $what == 'title' ) {
81 $matches = $search->searchTitle( $query );
82 } elseif ( $what == 'nearmatch' ) {
83 // near matches must receive the user input as provided, otherwise
84 // the near matches within namespaces are lost.
85 $matches = $search->getNearMatcher( $this->getConfig() )
86 ->getNearMatchResultSet( $params['search'] );
88 // We default to title searches; this is a terrible legacy
89 // of the way we initially set up the MySQL fulltext-based
90 // search engine with separate title and text fields.
91 // In the future, the default should be for a combined index.
93 $matches = $search->searchTitle( $query );
95 // Not all search engines support a separate title search,
96 // for instance the Lucene-based engine we use on Wikipedia.
97 // In this case, fall back to full-text search (which will
98 // include titles in it!)
99 if ( is_null( $matches ) ) {
101 $matches = $search->searchText( $query );
105 if ( $matches instanceof Status
) {
107 $matches = $status->getValue();
113 if ( $status->isOK() ) {
114 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
115 $this->getModuleName(),
119 $this->dieStatus( $status );
121 } elseif ( is_null( $matches ) ) {
122 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
125 if ( $resultPageSet === null ) {
126 $apiResult = $this->getResult();
127 // Add search meta data to result
128 if ( isset( $searchInfo['totalhits'] ) ) {
129 $totalhits = $matches->getTotalHits();
130 if ( $totalhits !== null ) {
131 $apiResult->addValue( [ 'query', 'searchinfo' ],
132 'totalhits', $totalhits );
135 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
136 $apiResult->addValue( [ 'query', 'searchinfo' ],
137 'suggestion', $matches->getSuggestionQuery() );
138 $apiResult->addValue( [ 'query', 'searchinfo' ],
139 'suggestionsnippet', $matches->getSuggestionSnippet() );
141 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
142 $apiResult->addValue( [ 'query', 'searchinfo' ],
143 'rewrittenquery', $matches->getQueryAfterRewrite() );
144 $apiResult->addValue( [ 'query', 'searchinfo' ],
145 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
149 // Add the search results to the result
150 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
153 $limit = $params['limit'];
155 if ( $matches->hasMoreResults() ) {
156 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
159 foreach ( $matches as $result ) {
161 // Silently skip broken and missing titles
162 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
166 if ( $resultPageSet === null ) {
167 $vals = $this->getSearchResultData( $result, $prop, $terms );
169 // Add item to results and see whether it fits
170 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
172 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
177 $titles[] = $result->getTitle();
181 // Here we assume interwiki results do not count with
182 // regular search results. We may want to reconsider this
183 // if we ever return a lot of interwiki results or want pagination
185 // Interwiki results inside main result set
186 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
187 if ( $canAddInterwiki ) {
188 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
189 SearchResultSet
::INLINE_RESULTS
);
192 // Interwiki results outside main result set
193 if ( $interwiki && $resultPageSet === null ) {
194 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
195 SearchResultSet
::SECONDARY_RESULTS
);
198 if ( $resultPageSet === null ) {
199 $apiResult->addIndexedTagName( [
200 'query', $this->getModuleName()
203 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
204 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
205 $current['index'] = $new['index'];
209 $resultPageSet->populateFromTitles( $titles );
210 $offset = $params['offset'] +
1;
211 foreach ( $titles as $index => $title ) {
212 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
218 * Assemble search result data.
219 * @param SearchResult $result Search result
220 * @param array $prop Props to extract (as keys)
221 * @param array $terms Terms list
222 * @return array|null Result data or null if result is broken in some way.
224 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
225 // Silently skip broken and missing titles
226 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
232 $title = $result->getTitle();
233 ApiQueryBase
::addTitleInfo( $vals, $title );
234 $vals['pageid'] = $title->getArticleID();
236 if ( isset( $prop['size'] ) ) {
237 $vals['size'] = $result->getByteSize();
239 if ( isset( $prop['wordcount'] ) ) {
240 $vals['wordcount'] = $result->getWordCount();
242 if ( isset( $prop['snippet'] ) ) {
243 $vals['snippet'] = $result->getTextSnippet( $terms );
245 if ( isset( $prop['timestamp'] ) ) {
246 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
248 if ( isset( $prop['titlesnippet'] ) ) {
249 $vals['titlesnippet'] = $result->getTitleSnippet();
251 if ( isset( $prop['categorysnippet'] ) ) {
252 $vals['categorysnippet'] = $result->getCategorySnippet();
254 if ( !is_null( $result->getRedirectTitle() ) ) {
255 if ( isset( $prop['redirecttitle'] ) ) {
256 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
258 if ( isset( $prop['redirectsnippet'] ) ) {
259 $vals['redirectsnippet'] = $result->getRedirectSnippet();
262 if ( !is_null( $result->getSectionTitle() ) ) {
263 if ( isset( $prop['sectiontitle'] ) ) {
264 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
266 if ( isset( $prop['sectionsnippet'] ) ) {
267 $vals['sectionsnippet'] = $result->getSectionSnippet();
270 if ( isset( $prop['isfilematch'] ) ) {
271 $vals['isfilematch'] = $result->isFileMatch();
274 if ( isset( $prop['extensiondata'] ) ) {
275 $extra = $result->getExtensionData();
276 // Add augmented data to the result. The data would be organized as a map:
277 // augmentorName => data
279 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
287 * Add interwiki results as a section in query results.
288 * @param SearchResultSet $matches
289 * @param ApiResult $apiResult
290 * @param array $prop Props to extract (as keys)
291 * @param array $terms Terms list
292 * @param string $section Section name where results would go
293 * @param int $type Interwiki result type
294 * @return int|null Number of total hits in the data or null if none was produced
296 private function addInterwikiResults(
297 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
298 $terms, $section, $type
301 if ( $matches->hasInterwikiResults( $type ) ) {
302 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
303 // Include number of results if requested
304 $totalhits +
= $interwikiMatches->getTotalHits();
306 foreach ( $interwikiMatches as $result ) {
307 $title = $result->getTitle();
308 $vals = $this->getSearchResultData( $result, $prop, $terms );
310 $vals['namespace'] = $result->getInterwikiNamespaceText();
311 $vals['title'] = $title->getText();
312 $vals['url'] = $title->getFullURL();
314 // Add item to results and see whether it fits
315 $fit = $apiResult->addValue( [
317 $section . $this->getModuleName(),
318 $result->getInterwikiPrefix()
322 // We hit the limit. We can't really provide any meaningful
323 // pagination info so just bail out
328 if ( $totalhits !== null ) {
329 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
330 $apiResult->addIndexedTagName( [
331 'query', $section . $this->getModuleName()
338 public function getCacheMode( $params ) {
342 public function getAllowedParams() {
343 if ( $this->allowedParams
!== null ) {
344 return $this->allowedParams
;
347 $this->allowedParams
= $this->buildCommonApiParams() +
[
349 ApiBase
::PARAM_TYPE
=> [
356 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
357 ApiBase
::PARAM_TYPE
=> [
362 ApiBase
::PARAM_ISMULTI
=> true,
365 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
366 ApiBase
::PARAM_TYPE
=> [
378 'score', // deprecated
379 'hasrelated', // deprecated
382 ApiBase
::PARAM_ISMULTI
=> true,
383 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
384 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
389 'interwiki' => false,
390 'enablerewrites' => false,
393 // If we have more than one engine the list of available sorts is
394 // difficult to represent. For now don't expose it.
395 $alternatives = MediaWiki\MediaWikiServices
::getInstance()
396 ->getSearchEngineConfig()
398 if ( count( $alternatives ) == 1 ) {
399 $this->allowedParams
['sort'] = [
400 ApiBase
::PARAM_DFLT
=> 'relevance',
401 ApiBase
::PARAM_TYPE
=> MediaWiki\MediaWikiServices
::getInstance()
407 return $this->allowedParams
;
410 public function getSearchProfileParams() {
413 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
414 'help-message' => 'apihelp-query+search-param-qiprofile',
419 protected function getExamplesMessages() {
421 'action=query&list=search&srsearch=meaning'
422 => 'apihelp-query+search-example-simple',
423 'action=query&list=search&srwhat=text&srsearch=meaning'
424 => 'apihelp-query+search-example-text',
425 'action=query&generator=search&gsrsearch=meaning&prop=info'
426 => 'apihelp-query+search-example-generator',
430 public function getHelpUrls() {
431 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';