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->logFeatureUsage( 'action=search&srprop=hasrelated' );
68 $this->setWarning( 'srprop=hasrelated has been deprecated' );
70 if ( isset( $prop['score'] ) ) {
71 $this->logFeatureUsage( 'action=search&srprop=score' );
72 $this->setWarning( 'srprop=score has been deprecated' );
75 // Create search engine instance and set options
76 $search = $this->buildSearchEngine( $params );
77 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
78 $search->setFeatureData( 'interwiki', (bool)$interwiki );
80 $query = $search->transformSearchTerm( $query );
81 $query = $search->replacePrefixes( $query );
83 // Perform the actual search
84 if ( $what == 'text' ) {
85 $matches = $search->searchText( $query );
86 } elseif ( $what == 'title' ) {
87 $matches = $search->searchTitle( $query );
88 } elseif ( $what == 'nearmatch' ) {
89 // near matches must receive the user input as provided, otherwise
90 // the near matches within namespaces are lost.
91 $matches = $search->getNearMatcher( $this->getConfig() )
92 ->getNearMatchResultSet( $params['search'] );
94 // We default to title searches; this is a terrible legacy
95 // of the way we initially set up the MySQL fulltext-based
96 // search engine with separate title and text fields.
97 // In the future, the default should be for a combined index.
99 $matches = $search->searchTitle( $query );
101 // Not all search engines support a separate title search,
102 // for instance the Lucene-based engine we use on Wikipedia.
103 // In this case, fall back to full-text search (which will
104 // include titles in it!)
105 if ( is_null( $matches ) ) {
107 $matches = $search->searchText( $query );
110 if ( is_null( $matches ) ) {
111 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
112 } elseif ( $matches instanceof Status
&& !$matches->isGood() ) {
113 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
116 if ( $resultPageSet === null ) {
117 $apiResult = $this->getResult();
118 // Add search meta data to result
119 if ( isset( $searchInfo['totalhits'] ) ) {
120 $totalhits = $matches->getTotalHits();
121 if ( $totalhits !== null ) {
122 $apiResult->addValue( [ 'query', 'searchinfo' ],
123 'totalhits', $totalhits );
126 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
127 $apiResult->addValue( [ 'query', 'searchinfo' ],
128 'suggestion', $matches->getSuggestionQuery() );
129 $apiResult->addValue( [ 'query', 'searchinfo' ],
130 'suggestionsnippet', $matches->getSuggestionSnippet() );
132 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
133 $apiResult->addValue( [ 'query', 'searchinfo' ],
134 'rewrittenquery', $matches->getQueryAfterRewrite() );
135 $apiResult->addValue( [ 'query', 'searchinfo' ],
136 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
140 // Add the search results to the result
141 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
144 $result = $matches->next();
145 $limit = $params['limit'];
148 if ( ++
$count > $limit ) {
149 // We've reached the one extra which shows that there are
150 // additional items to be had. Stop here...
151 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
155 // Silently skip broken and missing titles
156 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
157 $result = $matches->next();
161 $title = $result->getTitle();
162 if ( $resultPageSet === null ) {
164 ApiQueryBase
::addTitleInfo( $vals, $title );
166 if ( isset( $prop['snippet'] ) ) {
167 $vals['snippet'] = $result->getTextSnippet( $terms );
169 if ( isset( $prop['size'] ) ) {
170 $vals['size'] = $result->getByteSize();
172 if ( isset( $prop['wordcount'] ) ) {
173 $vals['wordcount'] = $result->getWordCount();
175 if ( isset( $prop['timestamp'] ) ) {
176 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
178 if ( isset( $prop['titlesnippet'] ) ) {
179 $vals['titlesnippet'] = $result->getTitleSnippet();
181 if ( isset( $prop['categorysnippet'] ) ) {
182 $vals['categorysnippet'] = $result->getCategorySnippet();
184 if ( !is_null( $result->getRedirectTitle() ) ) {
185 if ( isset( $prop['redirecttitle'] ) ) {
186 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
188 if ( isset( $prop['redirectsnippet'] ) ) {
189 $vals['redirectsnippet'] = $result->getRedirectSnippet();
192 if ( !is_null( $result->getSectionTitle() ) ) {
193 if ( isset( $prop['sectiontitle'] ) ) {
194 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
196 if ( isset( $prop['sectionsnippet'] ) ) {
197 $vals['sectionsnippet'] = $result->getSectionSnippet();
200 if ( isset( $prop['isfilematch'] ) ) {
201 $vals['isfilematch'] = $result->isFileMatch();
204 // Add item to results and see whether it fits
205 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
208 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
215 $result = $matches->next();
218 $hasInterwikiResults = false;
220 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
221 foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
222 $hasInterwikiResults = true;
224 // Include number of results if requested
225 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
226 $totalhits +
= $interwikiMatches->getTotalHits();
229 $result = $interwikiMatches->next();
231 $title = $result->getTitle();
233 if ( $resultPageSet === null ) {
235 'namespace' => $result->getInterwikiNamespaceText(),
236 'title' => $title->getText(),
237 'url' => $title->getFullURL(),
240 // Add item to results and see whether it fits
241 $fit = $apiResult->addValue(
242 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
248 // We hit the limit. We can't really provide any meaningful
249 // pagination info so just bail out
256 $result = $interwikiMatches->next();
259 if ( $totalhits !== null ) {
260 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
261 'totalhits', $totalhits );
265 if ( $resultPageSet === null ) {
266 $apiResult->addIndexedTagName( [
267 'query', $this->getModuleName()
269 if ( $hasInterwikiResults ) {
270 $apiResult->addIndexedTagName( [
271 'query', 'interwiki' . $this->getModuleName()
275 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
276 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
277 $current['index'] = $new['index'];
281 $resultPageSet->populateFromTitles( $titles );
282 $offset = $params['offset'] +
1;
283 foreach ( $titles as $index => $title ) {
284 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
289 public function getCacheMode( $params ) {
293 public function getAllowedParams() {
294 if ( $this->allowedParams
!== null ) {
295 return $this->allowedParams
;
298 $this->allowedParams
= $this->buildCommonApiParams() +
[
300 ApiBase
::PARAM_TYPE
=> [
307 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
308 ApiBase
::PARAM_TYPE
=> [
313 ApiBase
::PARAM_ISMULTI
=> true,
316 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
317 ApiBase
::PARAM_TYPE
=> [
329 'score', // deprecated
330 'hasrelated', // deprecated
332 ApiBase
::PARAM_ISMULTI
=> true,
333 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
335 'interwiki' => false,
336 'enablerewrites' => false,
339 return $this->allowedParams
;
342 public function getSearchProfileParams() {
345 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
346 'help-message' => 'apihelp-query+search-param-qiprofile',
351 protected function getExamplesMessages() {
353 'action=query&list=search&srsearch=meaning'
354 => 'apihelp-query+search-example-simple',
355 'action=query&list=search&srwhat=text&srsearch=meaning'
356 => 'apihelp-query+search-example-text',
357 'action=query&generator=search&gsrsearch=meaning&prop=info'
358 => 'apihelp-query+search-example-generator',
362 public function getHelpUrls() {
363 return 'https://www.mediawiki.org/wiki/API:Search';