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
28 * Query module to perform full text search within wiki titles and content
32 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
35 /** @var array list of api allowed params */
36 private $allowedParams;
38 public function __construct( ApiQuery
$query, $moduleName ) {
39 parent
::__construct( $query, $moduleName, 'sr' );
42 public function execute() {
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
51 * @param ApiPageSet $resultPageSet
54 private function run( $resultPageSet = null ) {
56 $params = $this->extractRequestParams();
59 $query = $params['search'];
60 $what = $params['what'];
61 $interwiki = $params['interwiki'];
62 $searchInfo = array_flip( $params['info'] );
63 $prop = array_flip( $params['prop'] );
65 // Deprecated parameters
66 if ( isset( $prop['hasrelated'] ) ) {
67 $this->addDeprecation(
68 [ 'apiwarn-deprecation-parameter', 'srprop=hasrelated' ], 'action=search&srprop=hasrelated'
71 if ( isset( $prop['score'] ) ) {
72 $this->addDeprecation(
73 [ 'apiwarn-deprecation-parameter', 'srprop=score' ], 'action=search&srprop=score'
77 // Create search engine instance and set options
78 $search = $this->buildSearchEngine( $params );
79 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
80 $search->setFeatureData( 'interwiki', (bool)$interwiki );
82 $query = $search->transformSearchTerm( $query );
83 $query = $search->replacePrefixes( $query );
85 // Perform the actual search
86 if ( $what == 'text' ) {
87 $matches = $search->searchText( $query );
88 } elseif ( $what == 'title' ) {
89 $matches = $search->searchTitle( $query );
90 } elseif ( $what == 'nearmatch' ) {
91 // near matches must receive the user input as provided, otherwise
92 // the near matches within namespaces are lost.
93 $matches = $search->getNearMatcher( $this->getConfig() )
94 ->getNearMatchResultSet( $params['search'] );
96 // We default to title searches; this is a terrible legacy
97 // of the way we initially set up the MySQL fulltext-based
98 // search engine with separate title and text fields.
99 // In the future, the default should be for a combined index.
101 $matches = $search->searchTitle( $query );
103 // Not all search engines support a separate title search,
104 // for instance the Lucene-based engine we use on Wikipedia.
105 // In this case, fall back to full-text search (which will
106 // include titles in it!)
107 if ( is_null( $matches ) ) {
109 $matches = $search->searchText( $query );
113 if ( $matches instanceof Status
) {
115 $matches = $status->getValue();
121 if ( $status->isOK() ) {
122 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
123 $this->getModuleName(),
127 $this->dieStatus( $status );
129 } elseif ( is_null( $matches ) ) {
130 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
133 if ( $resultPageSet === null ) {
134 $apiResult = $this->getResult();
135 // Add search meta data to result
136 if ( isset( $searchInfo['totalhits'] ) ) {
137 $totalhits = $matches->getTotalHits();
138 if ( $totalhits !== null ) {
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'totalhits', $totalhits );
143 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
144 $apiResult->addValue( [ 'query', 'searchinfo' ],
145 'suggestion', $matches->getSuggestionQuery() );
146 $apiResult->addValue( [ 'query', 'searchinfo' ],
147 'suggestionsnippet', $matches->getSuggestionSnippet() );
149 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
150 $apiResult->addValue( [ 'query', 'searchinfo' ],
151 'rewrittenquery', $matches->getQueryAfterRewrite() );
152 $apiResult->addValue( [ 'query', 'searchinfo' ],
153 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
157 // Add the search results to the result
158 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
161 $result = $matches->next();
162 $limit = $params['limit'];
165 if ( ++
$count > $limit ) {
166 // We've reached the one extra which shows that there are
167 // additional items to be had. Stop here...
168 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
172 // Silently skip broken and missing titles
173 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
177 if ( $resultPageSet === null ) {
178 $vals = $this->getSearchResultData( $result, $prop, $terms );
180 // Add item to results and see whether it fits
181 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
183 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
188 $titles[] = $result->getTitle();
191 $result = $matches->next();
194 // Here we assume interwiki results do not count with
195 // regular search results. We may want to reconsider this
196 // if we ever return a lot of interwiki results or want pagination
198 // Interwiki results inside main result set
199 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
200 if ( $canAddInterwiki ) {
201 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
202 SearchResultSet
::INLINE_RESULTS
);
205 // Interwiki results outside main result set
206 if ( $interwiki && $resultPageSet === null ) {
207 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
208 SearchResultSet
::SECONDARY_RESULTS
);
211 if ( $resultPageSet === null ) {
212 $apiResult->addIndexedTagName( [
213 'query', $this->getModuleName()
216 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
217 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
218 $current['index'] = $new['index'];
222 $resultPageSet->populateFromTitles( $titles );
223 $offset = $params['offset'] +
1;
224 foreach ( $titles as $index => $title ) {
225 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
231 * Assemble search result data.
232 * @param SearchResult $result Search result
233 * @param array $prop Props to extract (as keys)
234 * @param array $terms Terms list
235 * @return array|null Result data or null if result is broken in some way.
237 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
238 // Silently skip broken and missing titles
239 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
245 $title = $result->getTitle();
246 ApiQueryBase
::addTitleInfo( $vals, $title );
248 if ( isset( $prop['size'] ) ) {
249 $vals['size'] = $result->getByteSize();
251 if ( isset( $prop['wordcount'] ) ) {
252 $vals['wordcount'] = $result->getWordCount();
254 if ( isset( $prop['snippet'] ) ) {
255 $vals['snippet'] = $result->getTextSnippet( $terms );
257 if ( isset( $prop['timestamp'] ) ) {
258 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
260 if ( isset( $prop['titlesnippet'] ) ) {
261 $vals['titlesnippet'] = $result->getTitleSnippet();
263 if ( isset( $prop['categorysnippet'] ) ) {
264 $vals['categorysnippet'] = $result->getCategorySnippet();
266 if ( !is_null( $result->getRedirectTitle() ) ) {
267 if ( isset( $prop['redirecttitle'] ) ) {
268 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
270 if ( isset( $prop['redirectsnippet'] ) ) {
271 $vals['redirectsnippet'] = $result->getRedirectSnippet();
274 if ( !is_null( $result->getSectionTitle() ) ) {
275 if ( isset( $prop['sectiontitle'] ) ) {
276 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
278 if ( isset( $prop['sectionsnippet'] ) ) {
279 $vals['sectionsnippet'] = $result->getSectionSnippet();
282 if ( isset( $prop['isfilematch'] ) ) {
283 $vals['isfilematch'] = $result->isFileMatch();
289 * Add interwiki results as a section in query results.
290 * @param SearchResultSet $matches
291 * @param ApiResult $apiResult
292 * @param array $prop Props to extract (as keys)
293 * @param array $terms Terms list
294 * @param string $section Section name where results would go
295 * @param int $type Interwiki result type
296 * @return int|null Number of total hits in the data or null if none was produced
298 private function addInterwikiResults(
299 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
300 $terms, $section, $type
303 if ( $matches->hasInterwikiResults( $type ) ) {
304 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
305 // Include number of results if requested
306 $totalhits +
= $interwikiMatches->getTotalHits();
308 $result = $interwikiMatches->next();
310 $title = $result->getTitle();
311 $vals = $this->getSearchResultData( $result, $prop, $terms );
313 $vals['namespace'] = $result->getInterwikiNamespaceText();
314 $vals['title'] = $title->getText();
315 $vals['url'] = $title->getFullURL();
317 // Add item to results and see whether it fits
318 $fit = $apiResult->addValue( [
320 $section . $this->getModuleName(),
321 $result->getInterwikiPrefix()
325 // We hit the limit. We can't really provide any meaningful
326 // pagination info so just bail out
330 $result = $interwikiMatches->next();
333 if ( $totalhits !== null ) {
334 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
335 $apiResult->addIndexedTagName( [
336 'query', $section . $this->getModuleName()
343 public function getCacheMode( $params ) {
347 public function getAllowedParams() {
348 if ( $this->allowedParams
!== null ) {
349 return $this->allowedParams
;
352 $this->allowedParams
= $this->buildCommonApiParams() +
[
354 ApiBase
::PARAM_TYPE
=> [
361 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
362 ApiBase
::PARAM_TYPE
=> [
367 ApiBase
::PARAM_ISMULTI
=> true,
370 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
371 ApiBase
::PARAM_TYPE
=> [
383 'score', // deprecated
384 'hasrelated', // deprecated
386 ApiBase
::PARAM_ISMULTI
=> true,
387 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
389 'interwiki' => false,
390 'enablerewrites' => false,
393 return $this->allowedParams
;
396 public function getSearchProfileParams() {
399 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
400 'help-message' => 'apihelp-query+search-param-qiprofile',
405 protected function getExamplesMessages() {
407 'action=query&list=search&srsearch=meaning'
408 => 'apihelp-query+search-example-simple',
409 'action=query&list=search&srwhat=text&srsearch=meaning'
410 => 'apihelp-query+search-example-text',
411 'action=query&generator=search&gsrsearch=meaning&prop=info'
412 => 'apihelp-query+search-example-generator',
416 public function getHelpUrls() {
417 return 'https://www.mediawiki.org/wiki/API:Search';