Merge "Fix PerDbnameStatsdDataFactory metric prefix"
[lhc/web/wiklou.git] / includes / api / ApiQuerySearch.php
1 <?php
2 /**
3 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 /**
24 * Query module to perform full text search within wiki titles and content
25 *
26 * @ingroup API
27 */
28 class ApiQuerySearch extends ApiQueryGeneratorBase {
29 use SearchApi;
30
31 /** @var array list of api allowed params */
32 private $allowedParams;
33
34 public function __construct( ApiQuery $query, $moduleName ) {
35 parent::__construct( $query, $moduleName, 'sr' );
36 }
37
38 public function execute() {
39 $this->run();
40 }
41
42 public function executeGenerator( $resultPageSet ) {
43 $this->run( $resultPageSet );
44 }
45
46 /**
47 * @param ApiPageSet $resultPageSet
48 * @return void
49 */
50 private function run( $resultPageSet = null ) {
51 global $wgContLang;
52 $params = $this->extractRequestParams();
53
54 // Extract parameters
55 $query = $params['search'];
56 $what = $params['what'];
57 $interwiki = $params['interwiki'];
58 $searchInfo = array_flip( $params['info'] );
59 $prop = array_flip( $params['prop'] );
60
61 // Create search engine instance and set options
62 $search = $this->buildSearchEngine( $params );
63 if ( isset( $params['sort'] ) ) {
64 $search->setSort( $params['sort'] );
65 }
66 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
67 $search->setFeatureData( 'interwiki', (bool)$interwiki );
68
69 $nquery = $search->transformSearchTerm( $query );
70 if ( $nquery !== $query ) {
71 $query = $nquery;
72 wfDeprecated( 'SearchEngine::transformSearchTerm() (overridden by ' .
73 get_class( $search ) . ')', '1.32' );
74 }
75
76 $nquery = $search->replacePrefixes( $query );
77 if ( $nquery !== $query ) {
78 $query = $nquery;
79 wfDeprecated( 'SearchEngine::replacePrefixes() (overridden by ' .
80 get_class( $search ) . ')', '1.32' );
81 }
82 // Perform the actual search
83 if ( $what == 'text' ) {
84 $matches = $search->searchText( $query );
85 } elseif ( $what == 'title' ) {
86 $matches = $search->searchTitle( $query );
87 } elseif ( $what == 'nearmatch' ) {
88 // near matches must receive the user input as provided, otherwise
89 // the near matches within namespaces are lost.
90 $matches = $search->getNearMatcher( $this->getConfig() )
91 ->getNearMatchResultSet( $params['search'] );
92 } else {
93 // We default to title searches; this is a terrible legacy
94 // of the way we initially set up the MySQL fulltext-based
95 // search engine with separate title and text fields.
96 // In the future, the default should be for a combined index.
97 $what = 'title';
98 $matches = $search->searchTitle( $query );
99
100 // Not all search engines support a separate title search,
101 // for instance the Lucene-based engine we use on Wikipedia.
102 // In this case, fall back to full-text search (which will
103 // include titles in it!)
104 if ( is_null( $matches ) ) {
105 $what = 'text';
106 $matches = $search->searchText( $query );
107 }
108 }
109
110 if ( $matches instanceof Status ) {
111 $status = $matches;
112 $matches = $status->getValue();
113 } else {
114 $status = null;
115 }
116
117 if ( $status ) {
118 if ( $status->isOK() ) {
119 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
120 $this->getModuleName(),
121 $status
122 );
123 } else {
124 $this->dieStatus( $status );
125 }
126 } elseif ( is_null( $matches ) ) {
127 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
128 }
129
130 if ( $resultPageSet === null ) {
131 $apiResult = $this->getResult();
132 // Add search meta data to result
133 if ( isset( $searchInfo['totalhits'] ) ) {
134 $totalhits = $matches->getTotalHits();
135 if ( $totalhits !== null ) {
136 $apiResult->addValue( [ 'query', 'searchinfo' ],
137 'totalhits', $totalhits );
138 }
139 }
140 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
141 $apiResult->addValue( [ 'query', 'searchinfo' ],
142 'suggestion', $matches->getSuggestionQuery() );
143 $apiResult->addValue( [ 'query', 'searchinfo' ],
144 'suggestionsnippet', $matches->getSuggestionSnippet() );
145 }
146 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
147 $apiResult->addValue( [ 'query', 'searchinfo' ],
148 'rewrittenquery', $matches->getQueryAfterRewrite() );
149 $apiResult->addValue( [ 'query', 'searchinfo' ],
150 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
151 }
152 }
153
154 // Add the search results to the result
155 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
156 $titles = [];
157 $count = 0;
158 $limit = $params['limit'];
159
160 if ( $matches->hasMoreResults() ) {
161 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
162 }
163
164 foreach ( $matches as $result ) {
165 $count++;
166 // Silently skip broken and missing titles
167 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
168 continue;
169 }
170
171 if ( $resultPageSet === null ) {
172 $vals = $this->getSearchResultData( $result, $prop, $terms );
173 if ( $vals ) {
174 // Add item to results and see whether it fits
175 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
176 if ( !$fit ) {
177 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
178 break;
179 }
180 }
181 } else {
182 $titles[] = $result->getTitle();
183 }
184 }
185
186 // Here we assume interwiki results do not count with
187 // regular search results. We may want to reconsider this
188 // if we ever return a lot of interwiki results or want pagination
189 // for them.
190 // Interwiki results inside main result set
191 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
192 if ( $canAddInterwiki ) {
193 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
194 SearchResultSet::INLINE_RESULTS );
195 }
196
197 // Interwiki results outside main result set
198 if ( $interwiki && $resultPageSet === null ) {
199 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
200 SearchResultSet::SECONDARY_RESULTS );
201 }
202
203 if ( $resultPageSet === null ) {
204 $apiResult->addIndexedTagName( [
205 'query', $this->getModuleName()
206 ], 'p' );
207 } else {
208 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
209 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
210 $current['index'] = $new['index'];
211 }
212 return $current;
213 } );
214 $resultPageSet->populateFromTitles( $titles );
215 $offset = $params['offset'] + 1;
216 foreach ( $titles as $index => $title ) {
217 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
218 }
219 }
220 }
221
222 /**
223 * Assemble search result data.
224 * @param SearchResult $result Search result
225 * @param array $prop Props to extract (as keys)
226 * @param array $terms Terms list
227 * @return array|null Result data or null if result is broken in some way.
228 */
229 private function getSearchResultData( SearchResult $result, $prop, $terms ) {
230 // Silently skip broken and missing titles
231 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
232 return null;
233 }
234
235 $vals = [];
236
237 $title = $result->getTitle();
238 ApiQueryBase::addTitleInfo( $vals, $title );
239 $vals['pageid'] = $title->getArticleID();
240
241 if ( isset( $prop['size'] ) ) {
242 $vals['size'] = $result->getByteSize();
243 }
244 if ( isset( $prop['wordcount'] ) ) {
245 $vals['wordcount'] = $result->getWordCount();
246 }
247 if ( isset( $prop['snippet'] ) ) {
248 $vals['snippet'] = $result->getTextSnippet( $terms );
249 }
250 if ( isset( $prop['timestamp'] ) ) {
251 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
252 }
253 if ( isset( $prop['titlesnippet'] ) ) {
254 $vals['titlesnippet'] = $result->getTitleSnippet();
255 }
256 if ( isset( $prop['categorysnippet'] ) ) {
257 $vals['categorysnippet'] = $result->getCategorySnippet();
258 }
259 if ( !is_null( $result->getRedirectTitle() ) ) {
260 if ( isset( $prop['redirecttitle'] ) ) {
261 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
262 }
263 if ( isset( $prop['redirectsnippet'] ) ) {
264 $vals['redirectsnippet'] = $result->getRedirectSnippet();
265 }
266 }
267 if ( !is_null( $result->getSectionTitle() ) ) {
268 if ( isset( $prop['sectiontitle'] ) ) {
269 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
270 }
271 if ( isset( $prop['sectionsnippet'] ) ) {
272 $vals['sectionsnippet'] = $result->getSectionSnippet();
273 }
274 }
275 if ( isset( $prop['isfilematch'] ) ) {
276 $vals['isfilematch'] = $result->isFileMatch();
277 }
278
279 if ( isset( $prop['extensiondata'] ) ) {
280 $extra = $result->getExtensionData();
281 // Add augmented data to the result. The data would be organized as a map:
282 // augmentorName => data
283 if ( $extra ) {
284 $vals['extensiondata'] = ApiResult::addMetadataToResultVars( $extra );
285 }
286 }
287
288 return $vals;
289 }
290
291 /**
292 * Add interwiki results as a section in query results.
293 * @param SearchResultSet $matches
294 * @param ApiResult $apiResult
295 * @param array $prop Props to extract (as keys)
296 * @param array $terms Terms list
297 * @param string $section Section name where results would go
298 * @param int $type Interwiki result type
299 * @return int|null Number of total hits in the data or null if none was produced
300 */
301 private function addInterwikiResults(
302 SearchResultSet $matches, ApiResult $apiResult, $prop,
303 $terms, $section, $type
304 ) {
305 $totalhits = null;
306 if ( $matches->hasInterwikiResults( $type ) ) {
307 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
308 // Include number of results if requested
309 $totalhits += $interwikiMatches->getTotalHits();
310
311 foreach ( $interwikiMatches as $result ) {
312 $title = $result->getTitle();
313 $vals = $this->getSearchResultData( $result, $prop, $terms );
314
315 $vals['namespace'] = $result->getInterwikiNamespaceText();
316 $vals['title'] = $title->getText();
317 $vals['url'] = $title->getFullURL();
318
319 // Add item to results and see whether it fits
320 $fit = $apiResult->addValue( [
321 'query',
322 $section . $this->getModuleName(),
323 $result->getInterwikiPrefix()
324 ], null, $vals );
325
326 if ( !$fit ) {
327 // We hit the limit. We can't really provide any meaningful
328 // pagination info so just bail out
329 break;
330 }
331 }
332 }
333 if ( $totalhits !== null ) {
334 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
335 $apiResult->addIndexedTagName( [
336 'query', $section . $this->getModuleName()
337 ], 'p' );
338 }
339 }
340 return $totalhits;
341 }
342
343 public function getCacheMode( $params ) {
344 return 'public';
345 }
346
347 public function getAllowedParams() {
348 if ( $this->allowedParams !== null ) {
349 return $this->allowedParams;
350 }
351
352 $this->allowedParams = $this->buildCommonApiParams() + [
353 'what' => [
354 ApiBase::PARAM_TYPE => [
355 'title',
356 'text',
357 'nearmatch',
358 ]
359 ],
360 'info' => [
361 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
362 ApiBase::PARAM_TYPE => [
363 'totalhits',
364 'suggestion',
365 'rewrittenquery',
366 ],
367 ApiBase::PARAM_ISMULTI => true,
368 ],
369 'prop' => [
370 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
371 ApiBase::PARAM_TYPE => [
372 'size',
373 'wordcount',
374 'timestamp',
375 'snippet',
376 'titlesnippet',
377 'redirecttitle',
378 'redirectsnippet',
379 'sectiontitle',
380 'sectionsnippet',
381 'isfilematch',
382 'categorysnippet',
383 'score', // deprecated
384 'hasrelated', // deprecated
385 'extensiondata',
386 ],
387 ApiBase::PARAM_ISMULTI => true,
388 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
389 ApiBase::PARAM_DEPRECATED_VALUES => [
390 'score' => true,
391 'hasrelated' => true
392 ],
393 ],
394 'interwiki' => false,
395 'enablerewrites' => false,
396 ];
397
398 // If we have more than one engine the list of available sorts is
399 // difficult to represent. For now don't expose it.
400 $alternatives = MediaWiki\MediaWikiServices::getInstance()
401 ->getSearchEngineConfig()
402 ->getSearchTypes();
403 if ( count( $alternatives ) == 1 ) {
404 $this->allowedParams['sort'] = [
405 ApiBase::PARAM_DFLT => 'relevance',
406 ApiBase::PARAM_TYPE => MediaWiki\MediaWikiServices::getInstance()
407 ->newSearchEngine()
408 ->getValidSorts(),
409 ];
410 }
411
412 return $this->allowedParams;
413 }
414
415 public function getSearchProfileParams() {
416 return [
417 'qiprofile' => [
418 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
419 'help-message' => 'apihelp-query+search-param-qiprofile',
420 ],
421 ];
422 }
423
424 protected function getExamplesMessages() {
425 return [
426 'action=query&list=search&srsearch=meaning'
427 => 'apihelp-query+search-example-simple',
428 'action=query&list=search&srwhat=text&srsearch=meaning'
429 => 'apihelp-query+search-example-text',
430 'action=query&generator=search&gsrsearch=meaning&prop=info'
431 => 'apihelp-query+search-example-generator',
432 ];
433 }
434
435 public function getHelpUrls() {
436 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';
437 }
438 }