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 /** @var array list of api allowed params */
38 private $allowedParams;
40 public function __construct( ApiQuery
$query, $moduleName ) {
41 parent
::__construct( $query, $moduleName, 'sr' );
44 public function execute() {
48 public function executeGenerator( $resultPageSet ) {
49 $this->run( $resultPageSet );
53 * @param ApiPageSet $resultPageSet
56 private function run( $resultPageSet = null ) {
58 $params = $this->extractRequestParams();
61 $query = $params['search'];
62 $what = $params['what'];
63 $interwiki = $params['interwiki'];
64 $searchInfo = array_flip( $params['info'] );
65 $prop = array_flip( $params['prop'] );
67 // Deprecated parameters
68 if ( isset( $prop['hasrelated'] ) ) {
69 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
70 $this->setWarning( 'srprop=hasrelated has been deprecated' );
72 if ( isset( $prop['score'] ) ) {
73 $this->logFeatureUsage( 'action=search&srprop=score' );
74 $this->setWarning( 'srprop=score has been deprecated' );
77 // Create search engine instance and set options
78 $search = $this->buildSearchEngine( $params );
79 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
81 $query = $search->transformSearchTerm( $query );
82 $query = $search->replacePrefixes( $query );
84 // Perform the actual search
85 if ( $what == 'text' ) {
86 $matches = $search->searchText( $query );
87 } elseif ( $what == 'title' ) {
88 $matches = $search->searchTitle( $query );
89 } elseif ( $what == 'nearmatch' ) {
90 // near matches must receive the user input as provided, otherwise
91 // the near matches within namespaces are lost.
92 $matches = $search->getNearMatcher( $this->getConfig() )
93 ->getNearMatchResultSet( $params['search'] );
95 // We default to title searches; this is a terrible legacy
96 // of the way we initially set up the MySQL fulltext-based
97 // search engine with separate title and text fields.
98 // In the future, the default should be for a combined index.
100 $matches = $search->searchTitle( $query );
102 // Not all search engines support a separate title search,
103 // for instance the Lucene-based engine we use on Wikipedia.
104 // In this case, fall back to full-text search (which will
105 // include titles in it!)
106 if ( is_null( $matches ) ) {
108 $matches = $search->searchText( $query );
111 if ( is_null( $matches ) ) {
112 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
113 } elseif ( $matches instanceof Status
&& !$matches->isGood() ) {
114 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
117 if ( $resultPageSet === null ) {
118 $apiResult = $this->getResult();
119 // Add search meta data to result
120 if ( isset( $searchInfo['totalhits'] ) ) {
121 $totalhits = $matches->getTotalHits();
122 if ( $totalhits !== null ) {
123 $apiResult->addValue( [ 'query', 'searchinfo' ],
124 'totalhits', $totalhits );
127 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
128 $apiResult->addValue( [ 'query', 'searchinfo' ],
129 'suggestion', $matches->getSuggestionQuery() );
130 $apiResult->addValue( [ 'query', 'searchinfo' ],
131 'suggestionsnippet', $matches->getSuggestionSnippet() );
133 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
134 $apiResult->addValue( [ 'query', 'searchinfo' ],
135 'rewrittenquery', $matches->getQueryAfterRewrite() );
136 $apiResult->addValue( [ 'query', 'searchinfo' ],
137 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
141 // Add the search results to the result
142 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
145 $result = $matches->next();
146 $limit = $params['limit'];
149 if ( ++
$count > $limit ) {
150 // We've reached the one extra which shows that there are
151 // additional items to be had. Stop here...
152 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
156 // Silently skip broken and missing titles
157 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
158 $result = $matches->next();
162 $title = $result->getTitle();
163 if ( $resultPageSet === null ) {
165 ApiQueryBase
::addTitleInfo( $vals, $title );
167 if ( isset( $prop['snippet'] ) ) {
168 $vals['snippet'] = $result->getTextSnippet( $terms );
170 if ( isset( $prop['size'] ) ) {
171 $vals['size'] = $result->getByteSize();
173 if ( isset( $prop['wordcount'] ) ) {
174 $vals['wordcount'] = $result->getWordCount();
176 if ( isset( $prop['timestamp'] ) ) {
177 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
179 if ( isset( $prop['titlesnippet'] ) ) {
180 $vals['titlesnippet'] = $result->getTitleSnippet();
182 if ( isset( $prop['categorysnippet'] ) ) {
183 $vals['categorysnippet'] = $result->getCategorySnippet();
185 if ( !is_null( $result->getRedirectTitle() ) ) {
186 if ( isset( $prop['redirecttitle'] ) ) {
187 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
189 if ( isset( $prop['redirectsnippet'] ) ) {
190 $vals['redirectsnippet'] = $result->getRedirectSnippet();
193 if ( !is_null( $result->getSectionTitle() ) ) {
194 if ( isset( $prop['sectiontitle'] ) ) {
195 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
197 if ( isset( $prop['sectionsnippet'] ) ) {
198 $vals['sectionsnippet'] = $result->getSectionSnippet();
201 if ( isset( $prop['isfilematch'] ) ) {
202 $vals['isfilematch'] = $result->isFileMatch();
205 // Add item to results and see whether it fits
206 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
209 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
216 $result = $matches->next();
219 $hasInterwikiResults = false;
221 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
222 foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
223 $hasInterwikiResults = true;
225 // Include number of results if requested
226 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
227 $totalhits +
= $interwikiMatches->getTotalHits();
230 $result = $interwikiMatches->next();
232 $title = $result->getTitle();
234 if ( $resultPageSet === null ) {
236 'namespace' => $result->getInterwikiNamespaceText(),
237 'title' => $title->getText(),
238 'url' => $title->getFullUrl(),
241 // Add item to results and see whether it fits
242 $fit = $apiResult->addValue(
243 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
249 // We hit the limit. We can't really provide any meaningful
250 // pagination info so just bail out
257 $result = $interwikiMatches->next();
260 if ( $totalhits !== null ) {
261 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
262 'totalhits', $totalhits );
266 if ( $resultPageSet === null ) {
267 $apiResult->addIndexedTagName( [
268 'query', $this->getModuleName()
270 if ( $hasInterwikiResults ) {
271 $apiResult->addIndexedTagName( [
272 'query', 'interwiki' . $this->getModuleName()
276 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
277 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
278 $current['index'] = $new['index'];
282 $resultPageSet->populateFromTitles( $titles );
283 $offset = $params['offset'] +
1;
284 foreach ( $titles as $index => $title ) {
285 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
290 public function getCacheMode( $params ) {
294 public function getAllowedParams() {
295 if ( $this->allowedParams
!== null ) {
296 return $this->allowedParams
;
299 $this->allowedParams
= $this->buildCommonApiParams() +
[
301 ApiBase
::PARAM_TYPE
=> [
308 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
309 ApiBase
::PARAM_TYPE
=> [
314 ApiBase
::PARAM_ISMULTI
=> true,
317 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
318 ApiBase
::PARAM_TYPE
=> [
330 'score', // deprecated
331 'hasrelated', // deprecated
333 ApiBase
::PARAM_ISMULTI
=> true,
334 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
336 'interwiki' => false,
337 'enablerewrites' => false,
340 return $this->allowedParams
;
343 public function getSearchProfileParams() {
346 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
347 'help-message' => 'apihelp-query+search-param-qiprofile',
352 protected function getExamplesMessages() {
354 'action=query&list=search&srsearch=meaning'
355 => 'apihelp-query+search-example-simple',
356 'action=query&list=search&srwhat=text&srsearch=meaning'
357 => 'apihelp-query+search-example-text',
358 'action=query&generator=search&gsrsearch=meaning&prop=info'
359 => 'apihelp-query+search-example-generator',
363 public function getHelpUrls() {
364 return 'https://www.mediawiki.org/wiki/API:Search';