5 * Created on July 30, 2007
7 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 use MediaWiki\MediaWikiServices
;
30 * Query module to perform full text search within wiki titles and content
34 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
37 * When $wgSearchType is null, $wgSearchAlternatives[0] is null. Null isn't
38 * a valid option for an array for PARAM_TYPE, so we'll use a fake name
39 * that can't possibly be a class name and describes what the null behavior
42 const BACKEND_NULL_PARAM
= 'database-backed';
44 public function __construct( ApiQuery
$query, $moduleName ) {
45 parent
::__construct( $query, $moduleName, 'sr' );
48 public function execute() {
52 public function executeGenerator( $resultPageSet ) {
53 $this->run( $resultPageSet );
57 * @param ApiPageSet $resultPageSet
60 private function run( $resultPageSet = null ) {
62 $params = $this->extractRequestParams();
65 $limit = $params['limit'];
66 $query = $params['search'];
67 $what = $params['what'];
68 $interwiki = $params['interwiki'];
69 $searchInfo = array_flip( $params['info'] );
70 $prop = array_flip( $params['prop'] );
72 // Deprecated parameters
73 if ( isset( $prop['hasrelated'] ) ) {
74 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
75 $this->setWarning( 'srprop=hasrelated has been deprecated' );
77 if ( isset( $prop['score'] ) ) {
78 $this->logFeatureUsage( 'action=search&srprop=score' );
79 $this->setWarning( 'srprop=score has been deprecated' );
82 // Create search engine instance and set options
83 $type = isset( $params['backend'] ) && $params['backend'] != self
::BACKEND_NULL_PARAM ?
84 $params['backend'] : null;
85 $search = MediaWikiServices
::getInstance()->getSearchEngineFactory()->create( $type );
86 $search->setLimitOffset( $limit +
1, $params['offset'] );
87 $search->setNamespaces( $params['namespace'] );
88 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
90 $query = $search->transformSearchTerm( $query );
91 $query = $search->replacePrefixes( $query );
93 // Perform the actual search
94 if ( $what == 'text' ) {
95 $matches = $search->searchText( $query );
96 } elseif ( $what == 'title' ) {
97 $matches = $search->searchTitle( $query );
98 } elseif ( $what == 'nearmatch' ) {
99 // near matches must receive the user input as provided, otherwise
100 // the near matches within namespaces are lost.
101 $matches = $search->getNearMatcher( $this->getConfig() )
102 ->getNearMatchResultSet( $params['search'] );
104 // We default to title searches; this is a terrible legacy
105 // of the way we initially set up the MySQL fulltext-based
106 // search engine with separate title and text fields.
107 // In the future, the default should be for a combined index.
109 $matches = $search->searchTitle( $query );
111 // Not all search engines support a separate title search,
112 // for instance the Lucene-based engine we use on Wikipedia.
113 // In this case, fall back to full-text search (which will
114 // include titles in it!)
115 if ( is_null( $matches ) ) {
117 $matches = $search->searchText( $query );
120 if ( is_null( $matches ) ) {
121 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
122 } elseif ( $matches instanceof Status
&& !$matches->isGood() ) {
123 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
126 if ( $resultPageSet === null ) {
127 $apiResult = $this->getResult();
128 // Add search meta data to result
129 if ( isset( $searchInfo['totalhits'] ) ) {
130 $totalhits = $matches->getTotalHits();
131 if ( $totalhits !== null ) {
132 $apiResult->addValue( [ 'query', 'searchinfo' ],
133 'totalhits', $totalhits );
136 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'suggestion', $matches->getSuggestionQuery() );
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'suggestionsnippet', $matches->getSuggestionSnippet() );
142 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
143 $apiResult->addValue( [ 'query', 'searchinfo' ],
144 'rewrittenquery', $matches->getQueryAfterRewrite() );
145 $apiResult->addValue( [ 'query', 'searchinfo' ],
146 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
150 // Add the search results to the result
151 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
154 $result = $matches->next();
157 if ( ++
$count > $limit ) {
158 // We've reached the one extra which shows that there are
159 // additional items to be had. Stop here...
160 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
164 // Silently skip broken and missing titles
165 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
166 $result = $matches->next();
170 $title = $result->getTitle();
171 if ( $resultPageSet === null ) {
173 ApiQueryBase
::addTitleInfo( $vals, $title );
175 if ( isset( $prop['snippet'] ) ) {
176 $vals['snippet'] = $result->getTextSnippet( $terms );
178 if ( isset( $prop['size'] ) ) {
179 $vals['size'] = $result->getByteSize();
181 if ( isset( $prop['wordcount'] ) ) {
182 $vals['wordcount'] = $result->getWordCount();
184 if ( isset( $prop['timestamp'] ) ) {
185 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
187 if ( isset( $prop['titlesnippet'] ) ) {
188 $vals['titlesnippet'] = $result->getTitleSnippet();
190 if ( isset( $prop['categorysnippet'] ) ) {
191 $vals['categorysnippet'] = $result->getCategorySnippet();
193 if ( !is_null( $result->getRedirectTitle() ) ) {
194 if ( isset( $prop['redirecttitle'] ) ) {
195 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
197 if ( isset( $prop['redirectsnippet'] ) ) {
198 $vals['redirectsnippet'] = $result->getRedirectSnippet();
201 if ( !is_null( $result->getSectionTitle() ) ) {
202 if ( isset( $prop['sectiontitle'] ) ) {
203 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
205 if ( isset( $prop['sectionsnippet'] ) ) {
206 $vals['sectionsnippet'] = $result->getSectionSnippet();
209 if ( isset( $prop['isfilematch'] ) ) {
210 $vals['isfilematch'] = $result->isFileMatch();
213 // Add item to results and see whether it fits
214 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
217 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
224 $result = $matches->next();
227 $hasInterwikiResults = false;
229 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
230 foreach ( $matches->getInterwikiResults() as $matches ) {
231 $matches = $matches->getInterwikiResults();
232 $hasInterwikiResults = true;
234 // Include number of results if requested
235 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
236 $totalhits +
= $matches->getTotalHits();
239 $result = $matches->next();
241 $title = $result->getTitle();
243 if ( $resultPageSet === null ) {
245 'namespace' => $result->getInterwikiNamespaceText(),
246 'title' => $title->getText(),
247 'url' => $title->getFullUrl(),
250 // Add item to results and see whether it fits
251 $fit = $apiResult->addValue(
252 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
258 // We hit the limit. We can't really provide any meaningful
259 // pagination info so just bail out
266 $result = $matches->next();
269 if ( $totalhits !== null ) {
270 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
271 'totalhits', $totalhits );
275 if ( $resultPageSet === null ) {
276 $apiResult->addIndexedTagName( [
277 'query', $this->getModuleName()
279 if ( $hasInterwikiResults ) {
280 $apiResult->addIndexedTagName( [
281 'query', 'interwiki' . $this->getModuleName()
285 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
286 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
287 $current['index'] = $new['index'];
291 $resultPageSet->populateFromTitles( $titles );
292 $offset = $params['offset'] +
1;
293 foreach ( $titles as $index => $title ) {
294 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
299 public function getCacheMode( $params ) {
303 public function getAllowedParams() {
306 ApiBase
::PARAM_TYPE
=> 'string',
307 ApiBase
::PARAM_REQUIRED
=> true
310 ApiBase
::PARAM_DFLT
=> NS_MAIN
,
311 ApiBase
::PARAM_TYPE
=> 'namespace',
312 ApiBase
::PARAM_ISMULTI
=> true,
315 ApiBase
::PARAM_TYPE
=> [
322 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
323 ApiBase
::PARAM_TYPE
=> [
328 ApiBase
::PARAM_ISMULTI
=> true,
331 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
332 ApiBase
::PARAM_TYPE
=> [
344 'score', // deprecated
345 'hasrelated', // deprecated
347 ApiBase
::PARAM_ISMULTI
=> true,
348 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
351 ApiBase
::PARAM_DFLT
=> 0,
352 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
355 ApiBase
::PARAM_DFLT
=> 10,
356 ApiBase
::PARAM_TYPE
=> 'limit',
357 ApiBase
::PARAM_MIN
=> 1,
358 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_BIG1
,
359 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_BIG2
361 'interwiki' => false,
362 'enablerewrites' => false,
365 $searchConfig = MediaWikiServices
::getInstance()->getSearchEngineConfig();
366 $alternatives = $searchConfig->getSearchTypes();
367 if ( count( $alternatives ) > 1 ) {
368 if ( $alternatives[0] === null ) {
369 $alternatives[0] = self
::BACKEND_NULL_PARAM
;
371 $params['backend'] = [
372 ApiBase
::PARAM_DFLT
=> $searchConfig->getSearchType(),
373 ApiBase
::PARAM_TYPE
=> $alternatives,
380 protected function getExamplesMessages() {
382 'action=query&list=search&srsearch=meaning'
383 => 'apihelp-query+search-example-simple',
384 'action=query&list=search&srwhat=text&srsearch=meaning'
385 => 'apihelp-query+search-example-text',
386 'action=query&generator=search&gsrsearch=meaning&prop=info'
387 => 'apihelp-query+search-example-generator',
391 public function getHelpUrls() {
392 return 'https://www.mediawiki.org/wiki/API:Search';