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 $result = $matches->next();
146 $limit = $params['limit'];
149 if ( ++
$count > $limit ) {
150 // We've reached the one extra which shows that there are
151 // additional items to be had. Stop here...
152 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$params['limit'] );
156 // Silently skip broken and missing titles
157 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
158 $result = $matches->next();
162 if ( $resultPageSet === null ) {
163 $vals = $this->getSearchResultData( $result, $prop, $terms );
165 // Add item to results and see whether it fits
166 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
168 $this->setContinueEnumParameter( 'offset', $params['offset'] +
$count - 1 );
173 $titles[] = $result->getTitle();
176 $result = $matches->next();
179 // Here we assume interwiki results do not count with
180 // regular search results. We may want to reconsider this
181 // if we ever return a lot of interwiki results or want pagination
183 // Interwiki results inside main result set
184 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
185 if ( $canAddInterwiki ) {
186 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
187 SearchResultSet
::INLINE_RESULTS
);
190 // Interwiki results outside main result set
191 if ( $interwiki && $resultPageSet === null ) {
192 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
193 SearchResultSet
::SECONDARY_RESULTS
);
196 if ( $resultPageSet === null ) {
197 $apiResult->addIndexedTagName( [
198 'query', $this->getModuleName()
201 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
202 if ( !isset( $current['index'] ) ||
$new['index'] < $current['index'] ) {
203 $current['index'] = $new['index'];
207 $resultPageSet->populateFromTitles( $titles );
208 $offset = $params['offset'] +
1;
209 foreach ( $titles as $index => $title ) {
210 $resultPageSet->setGeneratorData( $title, [ 'index' => $index +
$offset ] );
216 * Assemble search result data.
217 * @param SearchResult $result Search result
218 * @param array $prop Props to extract (as keys)
219 * @param array $terms Terms list
220 * @return array|null Result data or null if result is broken in some way.
222 private function getSearchResultData( SearchResult
$result, $prop, $terms ) {
223 // Silently skip broken and missing titles
224 if ( $result->isBrokenTitle() ||
$result->isMissingRevision() ) {
230 $title = $result->getTitle();
231 ApiQueryBase
::addTitleInfo( $vals, $title );
232 $vals['pageid'] = $title->getArticleID();
234 if ( isset( $prop['size'] ) ) {
235 $vals['size'] = $result->getByteSize();
237 if ( isset( $prop['wordcount'] ) ) {
238 $vals['wordcount'] = $result->getWordCount();
240 if ( isset( $prop['snippet'] ) ) {
241 $vals['snippet'] = $result->getTextSnippet( $terms );
243 if ( isset( $prop['timestamp'] ) ) {
244 $vals['timestamp'] = wfTimestamp( TS_ISO_8601
, $result->getTimestamp() );
246 if ( isset( $prop['titlesnippet'] ) ) {
247 $vals['titlesnippet'] = $result->getTitleSnippet();
249 if ( isset( $prop['categorysnippet'] ) ) {
250 $vals['categorysnippet'] = $result->getCategorySnippet();
252 if ( !is_null( $result->getRedirectTitle() ) ) {
253 if ( isset( $prop['redirecttitle'] ) ) {
254 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
256 if ( isset( $prop['redirectsnippet'] ) ) {
257 $vals['redirectsnippet'] = $result->getRedirectSnippet();
260 if ( !is_null( $result->getSectionTitle() ) ) {
261 if ( isset( $prop['sectiontitle'] ) ) {
262 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
264 if ( isset( $prop['sectionsnippet'] ) ) {
265 $vals['sectionsnippet'] = $result->getSectionSnippet();
268 if ( isset( $prop['isfilematch'] ) ) {
269 $vals['isfilematch'] = $result->isFileMatch();
272 if ( isset( $prop['extensiondata'] ) ) {
273 $extra = $result->getExtensionData();
274 // Add augmented data to the result. The data would be organized as a map:
275 // augmentorName => data
277 $vals['extensiondata'] = ApiResult
::addMetadataToResultVars( $extra );
285 * Add interwiki results as a section in query results.
286 * @param SearchResultSet $matches
287 * @param ApiResult $apiResult
288 * @param array $prop Props to extract (as keys)
289 * @param array $terms Terms list
290 * @param string $section Section name where results would go
291 * @param int $type Interwiki result type
292 * @return int|null Number of total hits in the data or null if none was produced
294 private function addInterwikiResults(
295 SearchResultSet
$matches, ApiResult
$apiResult, $prop,
296 $terms, $section, $type
299 if ( $matches->hasInterwikiResults( $type ) ) {
300 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
301 // Include number of results if requested
302 $totalhits +
= $interwikiMatches->getTotalHits();
304 $result = $interwikiMatches->next();
306 $title = $result->getTitle();
307 $vals = $this->getSearchResultData( $result, $prop, $terms );
309 $vals['namespace'] = $result->getInterwikiNamespaceText();
310 $vals['title'] = $title->getText();
311 $vals['url'] = $title->getFullURL();
313 // Add item to results and see whether it fits
314 $fit = $apiResult->addValue( [
316 $section . $this->getModuleName(),
317 $result->getInterwikiPrefix()
321 // We hit the limit. We can't really provide any meaningful
322 // pagination info so just bail out
326 $result = $interwikiMatches->next();
329 if ( $totalhits !== null ) {
330 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
331 $apiResult->addIndexedTagName( [
332 'query', $section . $this->getModuleName()
339 public function getCacheMode( $params ) {
343 public function getAllowedParams() {
344 if ( $this->allowedParams
!== null ) {
345 return $this->allowedParams
;
348 $this->allowedParams
= $this->buildCommonApiParams() +
[
350 ApiBase
::PARAM_TYPE
=> [
357 ApiBase
::PARAM_DFLT
=> 'totalhits|suggestion|rewrittenquery',
358 ApiBase
::PARAM_TYPE
=> [
363 ApiBase
::PARAM_ISMULTI
=> true,
366 ApiBase
::PARAM_DFLT
=> 'size|wordcount|timestamp|snippet',
367 ApiBase
::PARAM_TYPE
=> [
379 'score', // deprecated
380 'hasrelated', // deprecated
383 ApiBase
::PARAM_ISMULTI
=> true,
384 ApiBase
::PARAM_HELP_MSG_PER_VALUE
=> [],
385 ApiBase
::PARAM_DEPRECATED_VALUES
=> [
390 'interwiki' => false,
391 'enablerewrites' => false,
394 return $this->allowedParams
;
397 public function getSearchProfileParams() {
400 'profile-type' => SearchEngine
::FT_QUERY_INDEP_PROFILE_TYPE
,
401 'help-message' => 'apihelp-query+search-param-qiprofile',
406 protected function getExamplesMessages() {
408 'action=query&list=search&srsearch=meaning'
409 => 'apihelp-query+search-example-simple',
410 'action=query&list=search&srwhat=text&srsearch=meaning'
411 => 'apihelp-query+search-example-text',
412 'action=query&generator=search&gsrsearch=meaning&prop=info'
413 => 'apihelp-query+search-example-generator',
417 public function getHelpUrls() {
418 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';