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'] );
79 $query = $search->transformSearchTerm( $query );
80 $query = $search->replacePrefixes( $query );
82 // Perform the actual search
83 if ( $what == 'text' ) {
84 $matches = $search->searchText( $query );
85 } elseif ( $what == 'title' ) {
86 $matches = $search->searchTitle( $query );
87 } elseif ( $what == 'nearmatch' ) {
88 // near matches must receive the user input as provided, otherwise
89 // the near matches within namespaces are lost.
90 $matches = $search->getNearMatcher( $this->getConfig() )
91 ->getNearMatchResultSet( $params['search'] );
93 // We default to title searches; this is a terrible legacy
94 // of the way we initially set up the MySQL fulltext-based
95 // search engine with separate title and text fields.
96 // In the future, the default should be for a combined index.
98 $matches = $search->searchTitle( $query );
100 // Not all search engines support a separate title search,
101 // for instance the Lucene-based engine we use on Wikipedia.
102 // In this case, fall back to full-text search (which will
103 // include titles in it!)
104 if ( is_null( $matches ) ) {
106 $matches = $search->searchText( $query );
109 if ( is_null( $matches ) ) {
110 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
111 } elseif ( $matches instanceof Status
&& !$matches->isGood() ) {
112 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
115 if ( $resultPageSet === null ) {
116 $apiResult = $this->getResult();
117 // Add search meta data to result
118 if ( isset( $searchInfo['totalhits'] ) ) {
119 $totalhits = $matches->getTotalHits();
120 if ( $totalhits !== null ) {
121 $apiResult->addValue( [ 'query', 'searchinfo' ],
122 'totalhits', $totalhits );
125 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
126 $apiResult->addValue( [ 'query', 'searchinfo' ],
127 'suggestion', $matches->getSuggestionQuery() );
128 $apiResult->addValue( [ 'query', 'searchinfo' ],
129 'suggestionsnippet', $matches->getSuggestionSnippet() );
131 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
132 $apiResult->addValue( [ 'query', 'searchinfo' ],
133 'rewrittenquery', $matches->getQueryAfterRewrite() );
134 $apiResult->addValue( [ 'query', 'searchinfo' ],
135 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
139 // Add the search results to the result
140 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
143 $result = $matches->next();
144 $limit = $params['limit'];
147 if ( ++
$count > $limit ) {
148 // We've reached the one extra which shows that there are
149 // additional items to be had. Stop here...
150 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
154 // Silently skip broken and missing titles
155 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
156 $result = $matches->next();
160 $title = $result->getTitle();
161 if ( $resultPageSet === null ) {
163 ApiQueryBase
::addTitleInfo( $vals, $title );
165 if ( isset( $prop['snippet'] ) ) {
166 $vals['snippet'] = $result->getTextSnippet( $terms );
168 if ( isset( $prop['size'] ) ) {
169 $vals['size'] = $result->getByteSize();
171 if ( isset( $prop['wordcount'] ) ) {
172 $vals['wordcount'] = $result->getWordCount();
174 if ( isset( $prop['timestamp'] ) ) {
175 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
177 if ( isset( $prop['titlesnippet'] ) ) {
178 $vals['titlesnippet'] = $result->getTitleSnippet();
180 if ( isset( $prop['categorysnippet'] ) ) {
181 $vals['categorysnippet'] = $result->getCategorySnippet();
183 if ( !is_null( $result->getRedirectTitle() ) ) {
184 if ( isset( $prop['redirecttitle'] ) ) {
185 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
187 if ( isset( $prop['redirectsnippet'] ) ) {
188 $vals['redirectsnippet'] = $result->getRedirectSnippet();
191 if ( !is_null( $result->getSectionTitle() ) ) {
192 if ( isset( $prop['sectiontitle'] ) ) {
193 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
195 if ( isset( $prop['sectionsnippet'] ) ) {
196 $vals['sectionsnippet'] = $result->getSectionSnippet();
199 if ( isset( $prop['isfilematch'] ) ) {
200 $vals['isfilematch'] = $result->isFileMatch();
203 // Add item to results and see whether it fits
204 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
207 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
214 $result = $matches->next();
217 $hasInterwikiResults = false;
219 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
220 foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
221 $hasInterwikiResults = true;
223 // Include number of results if requested
224 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
225 $totalhits +
= $interwikiMatches->getTotalHits();
228 $result = $interwikiMatches->next();
230 $title = $result->getTitle();
232 if ( $resultPageSet === null ) {
234 'namespace' => $result->getInterwikiNamespaceText(),
235 'title' => $title->getText(),
236 'url' => $title->getFullURL(),
239 // Add item to results and see whether it fits
240 $fit = $apiResult->addValue(
241 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
247 // We hit the limit. We can't really provide any meaningful
248 // pagination info so just bail out
255 $result = $interwikiMatches->next();
258 if ( $totalhits !== null ) {
259 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
260 'totalhits', $totalhits );
264 if ( $resultPageSet === null ) {
265 $apiResult->addIndexedTagName( [
266 'query', $this->getModuleName()
268 if ( $hasInterwikiResults ) {
269 $apiResult->addIndexedTagName( [
270 'query', 'interwiki' . $this->getModuleName()
274 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
275 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
276 $current['index'] = $new['index'];
280 $resultPageSet->populateFromTitles( $titles );
281 $offset = $params['offset'] +
1;
282 foreach ( $titles as $index => $title ) {
283 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
288 public function getCacheMode( $params ) {
292 public function getAllowedParams() {
293 if ( $this->allowedParams
!== null ) {
294 return $this->allowedParams
;
297 $this->allowedParams
= $this->buildCommonApiParams() +
[
299 ApiBase
::PARAM_TYPE
=> [
306 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
307 ApiBase
::PARAM_TYPE
=> [
312 ApiBase
::PARAM_ISMULTI
=> true,
315 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
316 ApiBase
::PARAM_TYPE
=> [
328 'score', // deprecated
329 'hasrelated', // deprecated
331 ApiBase
::PARAM_ISMULTI
=> true,
332 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
334 'interwiki' => false,
335 'enablerewrites' => false,
338 return $this->allowedParams
;
341 public function getSearchProfileParams() {
344 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
345 'help-message' => 'apihelp-query+search-param-qiprofile',
350 protected function getExamplesMessages() {
352 'action=query&list=search&srsearch=meaning'
353 => 'apihelp-query+search-example-simple',
354 'action=query&list=search&srwhat=text&srsearch=meaning'
355 => 'apihelp-query+search-example-text',
356 'action=query&generator=search&gsrsearch=meaning&prop=info'
357 => 'apihelp-query+search-example-generator',
361 public function getHelpUrls() {
362 return 'https://www.mediawiki.org/wiki/API:Search';