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 * When $wgSearchType is null, $wgSearchAlternatives[0] is null. Null isn't
36 * a valid option for an array for PARAM_TYPE, so we'll use a fake name
37 * that can't possibly be a class name and describes what the null behavior
40 const BACKEND_NULL_PARAM
= 'database-backed';
42 public function __construct( ApiQuery
$query, $moduleName ) {
43 parent
::__construct( $query, $moduleName, 'sr' );
46 public function execute() {
50 public function executeGenerator( $resultPageSet ) {
51 $this->run( $resultPageSet );
55 * @param ApiPageSet $resultPageSet
58 private function run( $resultPageSet = null ) {
60 $params = $this->extractRequestParams();
63 $limit = $params['limit'];
64 $query = $params['search'];
65 $what = $params['what'];
66 $interwiki = $params['interwiki'];
67 $searchInfo = array_flip( $params['info'] );
68 $prop = array_flip( $params['prop'] );
70 // Deprecated parameters
71 if ( isset( $prop['hasrelated'] ) ) {
72 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
73 $this->setWarning( 'srprop=hasrelated has been deprecated' );
75 if ( isset( $prop['score'] ) ) {
76 $this->logFeatureUsage( 'action=search&srprop=score' );
77 $this->setWarning( 'srprop=score has been deprecated' );
80 // Create search engine instance and set options
81 $search = isset( $params['backend'] ) && $params['backend'] != self
::BACKEND_NULL_PARAM ?
82 SearchEngine
::create( $params['backend'] ) : SearchEngine
::create();
83 $search->setLimitOffset( $limit +
1, $params['offset'] );
84 $search->setNamespaces( $params['namespace'] );
85 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
87 $query = $search->transformSearchTerm( $query );
88 $query = $search->replacePrefixes( $query );
90 // Perform the actual search
91 if ( $what == 'text' ) {
92 $matches = $search->searchText( $query );
93 } elseif ( $what == 'title' ) {
94 $matches = $search->searchTitle( $query );
95 } elseif ( $what == 'nearmatch' ) {
96 // near matches must receive the user input as provided, otherwise
97 // the near matches within namespaces are lost.
98 $matches = SearchEngine
::getNearMatchResultSet( $params['search'] );
100 // We default to title searches; this is a terrible legacy
101 // of the way we initially set up the MySQL fulltext-based
102 // search engine with separate title and text fields.
103 // In the future, the default should be for a combined index.
105 $matches = $search->searchTitle( $query );
107 // Not all search engines support a separate title search,
108 // for instance the Lucene-based engine we use on Wikipedia.
109 // In this case, fall back to full-text search (which will
110 // include titles in it!)
111 if ( is_null( $matches ) ) {
113 $matches = $search->searchText( $query );
116 if ( is_null( $matches ) ) {
117 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
118 } elseif ( $matches instanceof Status
&& !$matches->isGood() ) {
119 $this->dieUsage( $matches->getWikiText(), 'search-error' );
122 if ( $resultPageSet === null ) {
123 $apiResult = $this->getResult();
124 // Add search meta data to result
125 if ( isset( $searchInfo['totalhits'] ) ) {
126 $totalhits = $matches->getTotalHits();
127 if ( $totalhits !== null ) {
128 $apiResult->addValue( array( 'query', 'searchinfo' ),
129 'totalhits', $totalhits );
132 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
133 $apiResult->addValue( array( 'query', 'searchinfo' ),
134 'suggestion', $matches->getSuggestionQuery() );
135 $apiResult->addValue( array( 'query', 'searchinfo' ),
136 'suggestionsnippet', $matches->getSuggestionSnippet() );
138 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
139 $apiResult->addValue( array( 'query', 'searchinfo' ),
140 'rewrittenquery', $matches->getQueryAfterRewrite() );
141 $apiResult->addValue( array( 'query', 'searchinfo' ),
142 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
146 // Add the search results to the result
147 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
150 $result = $matches->next();
153 if ( ++
$count > $limit ) {
154 // We've reached the one extra which shows that there are
155 // additional items to be had. Stop here...
156 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
160 // Silently skip broken and missing titles
161 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
162 $result = $matches->next();
166 $title = $result->getTitle();
167 if ( $resultPageSet === null ) {
169 ApiQueryBase
::addTitleInfo( $vals, $title );
171 if ( isset( $prop['snippet'] ) ) {
172 $vals['snippet'] = $result->getTextSnippet( $terms );
174 if ( isset( $prop['size'] ) ) {
175 $vals['size'] = $result->getByteSize();
177 if ( isset( $prop['wordcount'] ) ) {
178 $vals['wordcount'] = $result->getWordCount();
180 if ( isset( $prop['timestamp'] ) ) {
181 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
183 if ( isset( $prop['titlesnippet'] ) ) {
184 $vals['titlesnippet'] = $result->getTitleSnippet();
186 if ( isset( $prop['categorysnippet'] ) ) {
187 $vals['categorysnippet'] = $result->getCategorySnippet();
189 if ( !is_null( $result->getRedirectTitle() ) ) {
190 if ( isset( $prop['redirecttitle'] ) ) {
191 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
193 if ( isset( $prop['redirectsnippet'] ) ) {
194 $vals['redirectsnippet'] = $result->getRedirectSnippet();
197 if ( !is_null( $result->getSectionTitle() ) ) {
198 if ( isset( $prop['sectiontitle'] ) ) {
199 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
201 if ( isset( $prop['sectionsnippet'] ) ) {
202 $vals['sectionsnippet'] = $result->getSectionSnippet();
205 if ( isset( $prop['isfilematch'] ) ) {
206 $vals['isfilematch'] = $result->isFileMatch();
209 // Add item to results and see whether it fits
210 $fit = $apiResult->addValue( array( 'query', $this->getModuleName() ),
213 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
220 $result = $matches->next();
223 $hasInterwikiResults = false;
225 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
226 foreach ( $matches->getInterwikiResults() as $matches ) {
227 $matches = $matches->getInterwikiResults();
228 $hasInterwikiResults = true;
230 // Include number of results if requested
231 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
232 $totalhits +
= $matches->getTotalHits();
235 $result = $matches->next();
237 $title = $result->getTitle();
239 if ( $resultPageSet === null ) {
241 'namespace' => $result->getInterwikiNamespaceText(),
242 'title' => $title->getText(),
243 'url' => $title->getFullUrl(),
246 // Add item to results and see whether it fits
247 $fit = $apiResult->addValue(
248 array( 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ),
254 // We hit the limit. We can't really provide any meaningful
255 // pagination info so just bail out
262 $result = $matches->next();
265 if ( $totalhits !== null ) {
266 $apiResult->addValue( array( 'query', 'interwikisearchinfo' ),
267 'totalhits', $totalhits );
271 if ( $resultPageSet === null ) {
272 $apiResult->addIndexedTagName( array(
273 'query', $this->getModuleName()
275 if ( $hasInterwikiResults ) {
276 $apiResult->addIndexedTagName( array(
277 'query', 'interwiki' . $this->getModuleName()
281 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
282 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
283 $current['index'] = $new['index'];
287 $resultPageSet->populateFromTitles( $titles );
288 $offset = $params['offset'] +
1;
289 foreach ( $titles as $index => $title ) {
290 $resultPageSet->setGeneratorData( $title, array( 'index' => $index +
$offset ) );
295 public function getCacheMode( $params ) {
299 public function getAllowedParams() {
302 ApiBase
::PARAM_TYPE
=> 'string',
303 ApiBase
::PARAM_REQUIRED
=> true
305 'namespace' => array(
306 ApiBase
::PARAM_DFLT
=> NS_MAIN
,
307 ApiBase
::PARAM_TYPE
=> 'namespace',
308 ApiBase
::PARAM_ISMULTI
=> true,
311 ApiBase
::PARAM_TYPE
=> array(
318 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
319 ApiBase
::PARAM_TYPE
=> array(
324 ApiBase
::PARAM_ISMULTI
=> true,
327 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
328 ApiBase
::PARAM_TYPE
=> array(
340 'score', // deprecated
341 'hasrelated', // deprecated
343 ApiBase
::PARAM_ISMULTI
=> true,
344 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> array(),
347 ApiBase
::PARAM_DFLT
=> 0,
348 ApiBase
::PARAM_HELP_MSG
=> 'api-help-param-continue',
351 ApiBase
::PARAM_DFLT
=> 10,
352 ApiBase
::PARAM_TYPE
=> 'limit',
353 ApiBase
::PARAM_MIN
=> 1,
354 ApiBase
::PARAM_MAX
=> ApiBase
::LIMIT_SML1
,
355 ApiBase
::PARAM_MAX2
=> ApiBase
::LIMIT_SML2
357 'interwiki' => false,
358 'enablerewrites' => false,
361 $alternatives = SearchEngine
::getSearchTypes();
362 if ( count( $alternatives ) > 1 ) {
363 if ( $alternatives[0] === null ) {
364 $alternatives[0] = self
::BACKEND_NULL_PARAM
;
366 $params['backend'] = array(
367 ApiBase
::PARAM_DFLT
=> $this->getConfig()->get( 'SearchType' ),
368 ApiBase
::PARAM_TYPE
=> $alternatives,
375 protected function getExamplesMessages() {
377 'action=query&list=search&srsearch=meaning'
378 => 'apihelp-query+search-example-simple',
379 'action=query&list=search&srwhat=text&srsearch=meaning'
380 => 'apihelp-query+search-example-text',
381 'action=query&generator=search&gsrsearch=meaning&prop=info'
382 => 'apihelp-query+search-example-generator',
386 public function getHelpUrls() {
387 return 'https://www.mediawiki.org/wiki/API:Search';