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 );
111 if ( $matches instanceof Status
) {
113 $matches = $status->getValue();
119 if ( $status->isOK() ) {
120 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
121 $this->getModuleName(),
125 $this->dieUsage( $status->getWikiText( false, false, 'en' ), 'search-error' );
127 } elseif ( is_null( $matches ) ) {
128 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
131 if ( $resultPageSet === null ) {
132 $apiResult = $this->getResult();
133 // Add search meta data to result
134 if ( isset( $searchInfo['totalhits'] ) ) {
135 $totalhits = $matches->getTotalHits();
136 if ( $totalhits !== null ) {
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'totalhits', $totalhits );
141 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
142 $apiResult->addValue( [ 'query', 'searchinfo' ],
143 'suggestion', $matches->getSuggestionQuery() );
144 $apiResult->addValue( [ 'query', 'searchinfo' ],
145 'suggestionsnippet', $matches->getSuggestionSnippet() );
147 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
148 $apiResult->addValue( [ 'query', 'searchinfo' ],
149 'rewrittenquery', $matches->getQueryAfterRewrite() );
150 $apiResult->addValue( [ 'query', 'searchinfo' ],
151 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
155 // Add the search results to the result
156 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
159 $result = $matches->next();
160 $limit = $params['limit'];
163 if ( ++
$count > $limit ) {
164 // We've reached the one extra which shows that there are
165 // additional items to be had. Stop here...
166 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
170 // Silently skip broken and missing titles
171 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
172 $result = $matches->next();
176 $title = $result->getTitle();
177 if ( $resultPageSet === null ) {
179 ApiQueryBase
::addTitleInfo( $vals, $title );
181 if ( isset( $prop['snippet'] ) ) {
182 $vals['snippet'] = $result->getTextSnippet( $terms );
184 if ( isset( $prop['size'] ) ) {
185 $vals['size'] = $result->getByteSize();
187 if ( isset( $prop['wordcount'] ) ) {
188 $vals['wordcount'] = $result->getWordCount();
190 if ( isset( $prop['timestamp'] ) ) {
191 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
193 if ( isset( $prop['titlesnippet'] ) ) {
194 $vals['titlesnippet'] = $result->getTitleSnippet();
196 if ( isset( $prop['categorysnippet'] ) ) {
197 $vals['categorysnippet'] = $result->getCategorySnippet();
199 if ( !is_null( $result->getRedirectTitle() ) ) {
200 if ( isset( $prop['redirecttitle'] ) ) {
201 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
203 if ( isset( $prop['redirectsnippet'] ) ) {
204 $vals['redirectsnippet'] = $result->getRedirectSnippet();
207 if ( !is_null( $result->getSectionTitle() ) ) {
208 if ( isset( $prop['sectiontitle'] ) ) {
209 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
211 if ( isset( $prop['sectionsnippet'] ) ) {
212 $vals['sectionsnippet'] = $result->getSectionSnippet();
215 if ( isset( $prop['isfilematch'] ) ) {
216 $vals['isfilematch'] = $result->isFileMatch();
219 // Add item to results and see whether it fits
220 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
223 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
230 $result = $matches->next();
233 $hasInterwikiResults = false;
235 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
236 foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
237 $hasInterwikiResults = true;
239 // Include number of results if requested
240 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
241 $totalhits +
= $interwikiMatches->getTotalHits();
244 $result = $interwikiMatches->next();
246 $title = $result->getTitle();
248 if ( $resultPageSet === null ) {
250 'namespace' => $result->getInterwikiNamespaceText(),
251 'title' => $title->getText(),
252 'url' => $title->getFullURL(),
255 // Add item to results and see whether it fits
256 $fit = $apiResult->addValue(
257 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
263 // We hit the limit. We can't really provide any meaningful
264 // pagination info so just bail out
271 $result = $interwikiMatches->next();
274 if ( $totalhits !== null ) {
275 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
276 'totalhits', $totalhits );
280 if ( $resultPageSet === null ) {
281 $apiResult->addIndexedTagName( [
282 'query', $this->getModuleName()
284 if ( $hasInterwikiResults ) {
285 $apiResult->addIndexedTagName( [
286 'query', 'interwiki' . $this->getModuleName()
290 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
291 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
292 $current['index'] = $new['index'];
296 $resultPageSet->populateFromTitles( $titles );
297 $offset = $params['offset'] +
1;
298 foreach ( $titles as $index => $title ) {
299 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
304 public function getCacheMode( $params ) {
308 public function getAllowedParams() {
309 if ( $this->allowedParams
!== null ) {
310 return $this->allowedParams
;
313 $this->allowedParams
= $this->buildCommonApiParams() +
[
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
=> [],
350 'interwiki' => false,
351 'enablerewrites' => false,
354 return $this->allowedParams
;
357 public function getSearchProfileParams() {
360 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
361 'help-message' => 'apihelp-query+search-param-qiprofile',
366 protected function getExamplesMessages() {
368 'action=query&list=search&srsearch=meaning'
369 => 'apihelp-query+search-example-simple',
370 'action=query&list=search&srwhat=text&srsearch=meaning'
371 => 'apihelp-query+search-example-text',
372 'action=query&generator=search&gsrsearch=meaning&prop=info'
373 => 'apihelp-query+search-example-generator',
377 public function getHelpUrls() {
378 return 'https://www.mediawiki.org/wiki/API:Search';