Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / api / ApiQuerySearch.php
blob05b693d552f2e7983b080e24263a00e4a2db770b
1 <?php
2 /**
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
24 * @file
27 /**
28 * Query module to perform full text search within wiki titles and content
30 * @ingroup API
32 class ApiQuerySearch extends ApiQueryGeneratorBase {
33 use SearchApi;
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() {
43 $this->run();
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
50 /**
51 * @param ApiPageSet $resultPageSet
52 * @return void
54 private function run( $resultPageSet = null ) {
55 global $wgContLang;
56 $params = $this->extractRequestParams();
58 // Extract parameters
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->addDeprecation(
68 [ 'apiwarn-deprecation-parameter', 'srprop=hasrelated' ], 'action=search&srprop=hasrelated'
71 if ( isset( $prop['score'] ) ) {
72 $this->addDeprecation(
73 [ 'apiwarn-deprecation-parameter', 'srprop=score' ], 'action=search&srprop=score'
77 // Create search engine instance and set options
78 $search = $this->buildSearchEngine( $params );
79 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
80 $search->setFeatureData( 'interwiki', (bool)$interwiki );
82 $query = $search->transformSearchTerm( $query );
83 $query = $search->replacePrefixes( $query );
85 // Perform the actual search
86 if ( $what == 'text' ) {
87 $matches = $search->searchText( $query );
88 } elseif ( $what == 'title' ) {
89 $matches = $search->searchTitle( $query );
90 } elseif ( $what == 'nearmatch' ) {
91 // near matches must receive the user input as provided, otherwise
92 // the near matches within namespaces are lost.
93 $matches = $search->getNearMatcher( $this->getConfig() )
94 ->getNearMatchResultSet( $params['search'] );
95 } else {
96 // We default to title searches; this is a terrible legacy
97 // of the way we initially set up the MySQL fulltext-based
98 // search engine with separate title and text fields.
99 // In the future, the default should be for a combined index.
100 $what = 'title';
101 $matches = $search->searchTitle( $query );
103 // Not all search engines support a separate title search,
104 // for instance the Lucene-based engine we use on Wikipedia.
105 // In this case, fall back to full-text search (which will
106 // include titles in it!)
107 if ( is_null( $matches ) ) {
108 $what = 'text';
109 $matches = $search->searchText( $query );
113 if ( $matches instanceof Status ) {
114 $status = $matches;
115 $matches = $status->getValue();
116 } else {
117 $status = null;
120 if ( $status ) {
121 if ( $status->isOK() ) {
122 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
123 $this->getModuleName(),
124 $status
126 } else {
127 $this->dieStatus( $status );
129 } elseif ( is_null( $matches ) ) {
130 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
133 if ( $resultPageSet === null ) {
134 $apiResult = $this->getResult();
135 // Add search meta data to result
136 if ( isset( $searchInfo['totalhits'] ) ) {
137 $totalhits = $matches->getTotalHits();
138 if ( $totalhits !== null ) {
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'totalhits', $totalhits );
143 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
144 $apiResult->addValue( [ 'query', 'searchinfo' ],
145 'suggestion', $matches->getSuggestionQuery() );
146 $apiResult->addValue( [ 'query', 'searchinfo' ],
147 'suggestionsnippet', $matches->getSuggestionSnippet() );
149 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
150 $apiResult->addValue( [ 'query', 'searchinfo' ],
151 'rewrittenquery', $matches->getQueryAfterRewrite() );
152 $apiResult->addValue( [ 'query', 'searchinfo' ],
153 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
157 // Add the search results to the result
158 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
159 $titles = [];
160 $count = 0;
161 $result = $matches->next();
162 $limit = $params['limit'];
164 while ( $result ) {
165 if ( ++$count > $limit ) {
166 // We've reached the one extra which shows that there are
167 // additional items to be had. Stop here...
168 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
169 break;
172 // Silently skip broken and missing titles
173 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
174 $result = $matches->next();
175 continue;
178 if ( $resultPageSet === null ) {
179 $vals = $this->getSearchResultData( $result, $prop, $terms );
180 if ( $vals ) {
181 // Add item to results and see whether it fits
182 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
183 if ( !$fit ) {
184 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
185 break;
188 } else {
189 $titles[] = $result->getTitle();
192 $result = $matches->next();
195 // Here we assume interwiki results do not count with
196 // regular search results. We may want to reconsider this
197 // if we ever return a lot of interwiki results or want pagination
198 // for them.
199 // Interwiki results inside main result set
200 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
201 if ( $canAddInterwiki ) {
202 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
203 SearchResultSet::INLINE_RESULTS );
206 // Interwiki results outside main result set
207 if ( $interwiki && $resultPageSet === null ) {
208 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
209 SearchResultSet::SECONDARY_RESULTS );
212 if ( $resultPageSet === null ) {
213 $apiResult->addIndexedTagName( [
214 'query', $this->getModuleName()
215 ], 'p' );
216 } else {
217 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
218 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
219 $current['index'] = $new['index'];
221 return $current;
222 } );
223 $resultPageSet->populateFromTitles( $titles );
224 $offset = $params['offset'] + 1;
225 foreach ( $titles as $index => $title ) {
226 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
232 * Assemble search result data.
233 * @param SearchResult $result Search result
234 * @param array $prop Props to extract (as keys)
235 * @param array $terms Terms list
236 * @return array|null Result data or null if result is broken in some way.
238 private function getSearchResultData( SearchResult $result, $prop, $terms ) {
239 // Silently skip broken and missing titles
240 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
241 return null;
244 $vals = [];
246 $title = $result->getTitle();
247 ApiQueryBase::addTitleInfo( $vals, $title );
249 if ( isset( $prop['size'] ) ) {
250 $vals['size'] = $result->getByteSize();
252 if ( isset( $prop['wordcount'] ) ) {
253 $vals['wordcount'] = $result->getWordCount();
255 if ( isset( $prop['snippet'] ) ) {
256 $vals['snippet'] = $result->getTextSnippet( $terms );
258 if ( isset( $prop['timestamp'] ) ) {
259 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
261 if ( isset( $prop['titlesnippet'] ) ) {
262 $vals['titlesnippet'] = $result->getTitleSnippet();
264 if ( isset( $prop['categorysnippet'] ) ) {
265 $vals['categorysnippet'] = $result->getCategorySnippet();
267 if ( !is_null( $result->getRedirectTitle() ) ) {
268 if ( isset( $prop['redirecttitle'] ) ) {
269 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
271 if ( isset( $prop['redirectsnippet'] ) ) {
272 $vals['redirectsnippet'] = $result->getRedirectSnippet();
275 if ( !is_null( $result->getSectionTitle() ) ) {
276 if ( isset( $prop['sectiontitle'] ) ) {
277 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
279 if ( isset( $prop['sectionsnippet'] ) ) {
280 $vals['sectionsnippet'] = $result->getSectionSnippet();
283 if ( isset( $prop['isfilematch'] ) ) {
284 $vals['isfilematch'] = $result->isFileMatch();
286 return $vals;
290 * Add interwiki results as a section in query results.
291 * @param SearchResultSet $matches
292 * @param ApiResult $apiResult
293 * @param array $prop Props to extract (as keys)
294 * @param array $terms Terms list
295 * @param string $section Section name where results would go
296 * @param int $type Interwiki result type
297 * @return int|null Number of total hits in the data or null if none was produced
299 private function addInterwikiResults(
300 SearchResultSet $matches, ApiResult $apiResult, $prop,
301 $terms, $section, $type
303 $totalhits = null;
304 if ( $matches->hasInterwikiResults( $type ) ) {
305 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
306 // Include number of results if requested
307 $totalhits += $interwikiMatches->getTotalHits();
309 $result = $interwikiMatches->next();
310 while ( $result ) {
311 $title = $result->getTitle();
312 $vals = $this->getSearchResultData( $result, $prop, $terms );
314 $vals['namespace'] = $result->getInterwikiNamespaceText();
315 $vals['title'] = $title->getText();
316 $vals['url'] = $title->getFullURL();
318 // Add item to results and see whether it fits
319 $fit = $apiResult->addValue( [
320 'query',
321 $section . $this->getModuleName(),
322 $result->getInterwikiPrefix()
323 ], null, $vals );
325 if ( !$fit ) {
326 // We hit the limit. We can't really provide any meaningful
327 // pagination info so just bail out
328 break;
331 $result = $interwikiMatches->next();
334 if ( $totalhits !== null ) {
335 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
336 $apiResult->addIndexedTagName( [
337 'query', $section . $this->getModuleName()
338 ], 'p' );
341 return $totalhits;
344 public function getCacheMode( $params ) {
345 return 'public';
348 public function getAllowedParams() {
349 if ( $this->allowedParams !== null ) {
350 return $this->allowedParams;
353 $this->allowedParams = $this->buildCommonApiParams() + [
354 'what' => [
355 ApiBase::PARAM_TYPE => [
356 'title',
357 'text',
358 'nearmatch',
361 'info' => [
362 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
363 ApiBase::PARAM_TYPE => [
364 'totalhits',
365 'suggestion',
366 'rewrittenquery',
368 ApiBase::PARAM_ISMULTI => true,
370 'prop' => [
371 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
372 ApiBase::PARAM_TYPE => [
373 'size',
374 'wordcount',
375 'timestamp',
376 'snippet',
377 'titlesnippet',
378 'redirecttitle',
379 'redirectsnippet',
380 'sectiontitle',
381 'sectionsnippet',
382 'isfilematch',
383 'categorysnippet',
384 'score', // deprecated
385 'hasrelated', // deprecated
387 ApiBase::PARAM_ISMULTI => true,
388 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
390 'interwiki' => false,
391 'enablerewrites' => false,
394 return $this->allowedParams;
397 public function getSearchProfileParams() {
398 return [
399 'qiprofile' => [
400 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
401 'help-message' => 'apihelp-query+search-param-qiprofile',
406 protected function getExamplesMessages() {
407 return [
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/API:Search';