3 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Query module to perform full text search within wiki titles and content
28 class ApiQuerySearch
extends ApiQueryGeneratorBase
{
31 /** @var array list of api allowed params */
32 private $allowedParams;
34 public function __construct( ApiQuery
$query, $moduleName ) {
35 parent
::__construct( $query, $moduleName, 'sr' );
38 public function execute() {
42 public function executeGenerator( $resultPageSet ) {
43 $this->run( $resultPageSet );
47 * @param ApiPageSet $resultPageSet
50 private function run( $resultPageSet = null ) {
52 $params = $this->extractRequestParams();
55 $query = $params['search'];
56 $what = $params['what'];
57 $interwiki = $params['interwiki'];
58 $searchInfo = array_flip( $params['info'] );
59 $prop = array_flip( $params['prop'] );
61 // Create search engine instance and set options
62 $search = $this->buildSearchEngine( $params );
63 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
64 $search->setFeatureData( 'interwiki', (bool)$interwiki );
66 $query = $search->transformSearchTerm( $query );
67 $query = $search->replacePrefixes( $query );
69 // Perform the actual search
70 if ( $what == 'text' ) {
71 $matches = $search->searchText( $query );
72 } elseif ( $what == 'title' ) {
73 $matches = $search->searchTitle( $query );
74 } elseif ( $what == 'nearmatch' ) {
75 // near matches must receive the user input as provided, otherwise
76 // the near matches within namespaces are lost.
77 $matches = $search->getNearMatcher( $this->getConfig() )
78 ->getNearMatchResultSet( $params['search'] );
80 // We default to title searches; this is a terrible legacy
81 // of the way we initially set up the MySQL fulltext-based
82 // search engine with separate title and text fields.
83 // In the future, the default should be for a combined index.
85 $matches = $search->searchTitle( $query );
87 // Not all search engines support a separate title search,
88 // for instance the Lucene-based engine we use on Wikipedia.
89 // In this case, fall back to full-text search (which will
90 // include titles in it!)
91 if ( is_null( $matches ) ) {
93 $matches = $search->searchText( $query );
97 if ( $matches instanceof Status
) {
99 $matches = $status->getValue();
105 if ( $status->isOK() ) {
106 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
107 $this->getModuleName(),
111 $this->dieStatus( $status );
113 } elseif ( is_null( $matches ) ) {
114 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
117 if ( $resultPageSet === null ) {
118 $apiResult = $this->getResult();
119 // Add search meta data to result
120 if ( isset( $searchInfo['totalhits'] ) ) {
121 $totalhits = $matches->getTotalHits();
122 if ( $totalhits !== null ) {
123 $apiResult->addValue( [ 'query', 'searchinfo' ],
124 'totalhits', $totalhits );
127 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
128 $apiResult->addValue( [ 'query', 'searchinfo' ],
129 'suggestion', $matches->getSuggestionQuery() );
130 $apiResult->addValue( [ 'query', 'searchinfo' ],
131 'suggestionsnippet', $matches->getSuggestionSnippet() );
133 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
134 $apiResult->addValue( [ 'query', 'searchinfo' ],
135 'rewrittenquery', $matches->getQueryAfterRewrite() );
136 $apiResult->addValue( [ 'query', 'searchinfo' ],
137 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
141 // Add the search results to the result
142 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
145 $limit = $params['limit'];
147 foreach ( $matches as $result ) {
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() ) {
160 if ( $resultPageSet === null ) {
161 $vals = $this->getSearchResultData( $result, $prop, $terms );
163 // Add item to results and see whether it fits
164 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
166 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
171 $titles[] = $result->getTitle();
175 // Here we assume interwiki results do not count with
176 // regular search results. We may want to reconsider this
177 // if we ever return a lot of interwiki results or want pagination
179 // Interwiki results inside main result set
180 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
181 if ( $canAddInterwiki ) {
182 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
183 SearchResultSet
::INLINE_RESULTS
);
186 // Interwiki results outside main result set
187 if ( $interwiki && $resultPageSet === null ) {
188 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
189 SearchResultSet
::SECONDARY_RESULTS
);
192 if ( $resultPageSet === null ) {
193 $apiResult->addIndexedTagName( [
194 'query', $this->getModuleName()
197 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
198 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
199 $current['index'] = $new['index'];
203 $resultPageSet->populateFromTitles( $titles );
204 $offset = $params['offset'] +
1;
205 foreach ( $titles as $index => $title ) {
206 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
212 * Assemble search result data.
213 * @param SearchResult $result Search result
214 * @param array $prop Props to extract (as keys)
215 * @param array $terms Terms list
216 * @return array|null Result data or null if result is broken in some way.
218 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
219 // Silently skip broken and missing titles
220 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
226 $title = $result->getTitle();
227 ApiQueryBase
::addTitleInfo( $vals, $title );
228 $vals['pageid'] = $title->getArticleID();
230 if ( isset( $prop['size'] ) ) {
231 $vals['size'] = $result->getByteSize();
233 if ( isset( $prop['wordcount'] ) ) {
234 $vals['wordcount'] = $result->getWordCount();
236 if ( isset( $prop['snippet'] ) ) {
237 $vals['snippet'] = $result->getTextSnippet( $terms );
239 if ( isset( $prop['timestamp'] ) ) {
240 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
242 if ( isset( $prop['titlesnippet'] ) ) {
243 $vals['titlesnippet'] = $result->getTitleSnippet();
245 if ( isset( $prop['categorysnippet'] ) ) {
246 $vals['categorysnippet'] = $result->getCategorySnippet();
248 if ( !is_null( $result->getRedirectTitle() ) ) {
249 if ( isset( $prop['redirecttitle'] ) ) {
250 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
252 if ( isset( $prop['redirectsnippet'] ) ) {
253 $vals['redirectsnippet'] = $result->getRedirectSnippet();
256 if ( !is_null( $result->getSectionTitle() ) ) {
257 if ( isset( $prop['sectiontitle'] ) ) {
258 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
260 if ( isset( $prop['sectionsnippet'] ) ) {
261 $vals['sectionsnippet'] = $result->getSectionSnippet();
264 if ( isset( $prop['isfilematch'] ) ) {
265 $vals['isfilematch'] = $result->isFileMatch();
268 if ( isset( $prop['extensiondata'] ) ) {
269 $extra = $result->getExtensionData();
270 // Add augmented data to the result. The data would be organized as a map:
271 // augmentorName => data
273 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
281 * Add interwiki results as a section in query results.
282 * @param SearchResultSet $matches
283 * @param ApiResult $apiResult
284 * @param array $prop Props to extract (as keys)
285 * @param array $terms Terms list
286 * @param string $section Section name where results would go
287 * @param int $type Interwiki result type
288 * @return int|null Number of total hits in the data or null if none was produced
290 private function addInterwikiResults(
291 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
292 $terms, $section, $type
295 if ( $matches->hasInterwikiResults( $type ) ) {
296 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
297 // Include number of results if requested
298 $totalhits +
= $interwikiMatches->getTotalHits();
300 foreach ( $interwikiMatches as $result ) {
301 $title = $result->getTitle();
302 $vals = $this->getSearchResultData( $result, $prop, $terms );
304 $vals['namespace'] = $result->getInterwikiNamespaceText();
305 $vals['title'] = $title->getText();
306 $vals['url'] = $title->getFullURL();
308 // Add item to results and see whether it fits
309 $fit = $apiResult->addValue( [
311 $section . $this->getModuleName(),
312 $result->getInterwikiPrefix()
316 // We hit the limit. We can't really provide any meaningful
317 // pagination info so just bail out
322 if ( $totalhits !== null ) {
323 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
324 $apiResult->addIndexedTagName( [
325 'query', $section . $this->getModuleName()
332 public function getCacheMode( $params ) {
336 public function getAllowedParams() {
337 if ( $this->allowedParams
!== null ) {
338 return $this->allowedParams
;
341 $this->allowedParams
= $this->buildCommonApiParams() +
[
343 ApiBase
::PARAM_TYPE
=> [
350 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
351 ApiBase
::PARAM_TYPE
=> [
356 ApiBase
::PARAM_ISMULTI
=> true,
359 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
360 ApiBase
::PARAM_TYPE
=> [
372 'score', // deprecated
373 'hasrelated', // deprecated
376 ApiBase
::PARAM_ISMULTI
=> true,
377 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
378 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
383 'interwiki' => false,
384 'enablerewrites' => false,
387 return $this->allowedParams
;
390 public function getSearchProfileParams() {
393 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
394 'help-message' => 'apihelp-query+search-param-qiprofile',
399 protected function getExamplesMessages() {
401 'action=query&list=search&srsearch=meaning'
402 => 'apihelp-query+search-example-simple',
403 'action=query&list=search&srwhat=text&srsearch=meaning'
404 => 'apihelp-query+search-example-text',
405 'action=query&generator=search&gsrsearch=meaning&prop=info'
406 => 'apihelp-query+search-example-generator',
410 public function getHelpUrls() {
411 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';