Merge "Optionally collect context in TestLogger"
[lhc/web/wiklou.git] / includes / api / ApiQuerySearch.php
1 <?php
2 /**
3 *
4 *
5 * Created on July 30, 2007
6 *
7 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
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.
13 *
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.
18 *
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
23 *
24 * @file
25 */
26
27 /**
28 * Query module to perform full text search within wiki titles and content
29 *
30 * @ingroup API
31 */
32 class ApiQuerySearch extends ApiQueryGeneratorBase {
33 use SearchApi;
34
35 /** @var array list of api allowed params */
36 private $allowedParams;
37
38 public function __construct( ApiQuery $query, $moduleName ) {
39 parent::__construct( $query, $moduleName, 'sr' );
40 }
41
42 public function execute() {
43 $this->run();
44 }
45
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
48 }
49
50 /**
51 * @param ApiPageSet $resultPageSet
52 * @return void
53 */
54 private function run( $resultPageSet = null ) {
55 global $wgContLang;
56 $params = $this->extractRequestParams();
57
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'] );
64
65 // Deprecated parameters
66 if ( isset( $prop['hasrelated'] ) ) {
67 $this->addDeprecation(
68 [ 'apiwarn-deprecation-parameter', 'srprop=hasrelated' ], 'action=search&srprop=hasrelated'
69 );
70 }
71 if ( isset( $prop['score'] ) ) {
72 $this->addDeprecation(
73 [ 'apiwarn-deprecation-parameter', 'srprop=score' ], 'action=search&srprop=score'
74 );
75 }
76
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 );
81
82 $query = $search->transformSearchTerm( $query );
83 $query = $search->replacePrefixes( $query );
84
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 );
102
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 );
110 }
111 }
112
113 if ( $matches instanceof Status ) {
114 $status = $matches;
115 $matches = $status->getValue();
116 } else {
117 $status = null;
118 }
119
120 if ( $status ) {
121 if ( $status->isOK() ) {
122 $this->getMain()->getErrorFormatter()->addMessagesFromStatus(
123 $this->getModuleName(),
124 $status
125 );
126 } else {
127 $this->dieStatus( $status );
128 }
129 } elseif ( is_null( $matches ) ) {
130 $this->dieWithError( [ 'apierror-searchdisabled', $what ], "search-{$what}-disabled" );
131 }
132
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 );
141 }
142 }
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() );
148 }
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() );
154 }
155 }
156
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'];
163
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;
170 }
171
172 // Silently skip broken and missing titles
173 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
174 return null;
175 }
176
177 if ( $resultPageSet === null ) {
178 $vals = $this->getSearchResultData( $result, $prop, $terms );
179 if ( $vals ) {
180 // Add item to results and see whether it fits
181 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
182 if ( !$fit ) {
183 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
184 break;
185 }
186 }
187 } else {
188 $titles[] = $result->getTitle();
189 }
190
191 $result = $matches->next();
192 }
193
194 // Here we assume interwiki results do not count with
195 // regular search results. We may want to reconsider this
196 // if we ever return a lot of interwiki results or want pagination
197 // for them.
198 // Interwiki results inside main result set
199 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
200 if ( $canAddInterwiki ) {
201 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
202 SearchResultSet::INLINE_RESULTS );
203 }
204
205 // Interwiki results outside main result set
206 if ( $interwiki && $resultPageSet === null ) {
207 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
208 SearchResultSet::SECONDARY_RESULTS );
209 }
210
211 if ( $resultPageSet === null ) {
212 $apiResult->addIndexedTagName( [
213 'query', $this->getModuleName()
214 ], 'p' );
215 } else {
216 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
217 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
218 $current['index'] = $new['index'];
219 }
220 return $current;
221 } );
222 $resultPageSet->populateFromTitles( $titles );
223 $offset = $params['offset'] + 1;
224 foreach ( $titles as $index => $title ) {
225 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
226 }
227 }
228 }
229
230 /**
231 * Assemble search result data.
232 * @param SearchResult $result Search result
233 * @param array $prop Props to extract (as keys)
234 * @param array $terms Terms list
235 * @return array|null Result data or null if result is broken in some way.
236 */
237 private function getSearchResultData( SearchResult $result, $prop, $terms ) {
238 // Silently skip broken and missing titles
239 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
240 return null;
241 }
242
243 $vals = [];
244
245 $title = $result->getTitle();
246 ApiQueryBase::addTitleInfo( $vals, $title );
247
248 if ( isset( $prop['size'] ) ) {
249 $vals['size'] = $result->getByteSize();
250 }
251 if ( isset( $prop['wordcount'] ) ) {
252 $vals['wordcount'] = $result->getWordCount();
253 }
254 if ( isset( $prop['snippet'] ) ) {
255 $vals['snippet'] = $result->getTextSnippet( $terms );
256 }
257 if ( isset( $prop['timestamp'] ) ) {
258 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
259 }
260 if ( isset( $prop['titlesnippet'] ) ) {
261 $vals['titlesnippet'] = $result->getTitleSnippet();
262 }
263 if ( isset( $prop['categorysnippet'] ) ) {
264 $vals['categorysnippet'] = $result->getCategorySnippet();
265 }
266 if ( !is_null( $result->getRedirectTitle() ) ) {
267 if ( isset( $prop['redirecttitle'] ) ) {
268 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
269 }
270 if ( isset( $prop['redirectsnippet'] ) ) {
271 $vals['redirectsnippet'] = $result->getRedirectSnippet();
272 }
273 }
274 if ( !is_null( $result->getSectionTitle() ) ) {
275 if ( isset( $prop['sectiontitle'] ) ) {
276 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
277 }
278 if ( isset( $prop['sectionsnippet'] ) ) {
279 $vals['sectionsnippet'] = $result->getSectionSnippet();
280 }
281 }
282 if ( isset( $prop['isfilematch'] ) ) {
283 $vals['isfilematch'] = $result->isFileMatch();
284 }
285 return $vals;
286 }
287
288 /**
289 * Add interwiki results as a section in query results.
290 * @param SearchResultSet $matches
291 * @param ApiResult $apiResult
292 * @param array $prop Props to extract (as keys)
293 * @param array $terms Terms list
294 * @param string $section Section name where results would go
295 * @param int $type Interwiki result type
296 * @return int|null Number of total hits in the data or null if none was produced
297 */
298 private function addInterwikiResults(
299 SearchResultSet $matches, ApiResult $apiResult, $prop,
300 $terms, $section, $type
301 ) {
302 $totalhits = null;
303 if ( $matches->hasInterwikiResults( $type ) ) {
304 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
305 // Include number of results if requested
306 $totalhits += $interwikiMatches->getTotalHits();
307
308 $result = $interwikiMatches->next();
309 while ( $result ) {
310 $title = $result->getTitle();
311 $vals = $this->getSearchResultData( $result, $prop, $terms );
312
313 $vals['namespace'] = $result->getInterwikiNamespaceText();
314 $vals['title'] = $title->getText();
315 $vals['url'] = $title->getFullURL();
316
317 // Add item to results and see whether it fits
318 $fit = $apiResult->addValue( [
319 'query',
320 $section . $this->getModuleName(),
321 $result->getInterwikiPrefix()
322 ], null, $vals );
323
324 if ( !$fit ) {
325 // We hit the limit. We can't really provide any meaningful
326 // pagination info so just bail out
327 break;
328 }
329
330 $result = $interwikiMatches->next();
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 ],
386 ApiBase::PARAM_ISMULTI => true,
387 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
388 ],
389 'interwiki' => false,
390 'enablerewrites' => false,
391 ];
392
393 return $this->allowedParams;
394 }
395
396 public function getSearchProfileParams() {
397 return [
398 'qiprofile' => [
399 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
400 'help-message' => 'apihelp-query+search-param-qiprofile',
401 ],
402 ];
403 }
404
405 protected function getExamplesMessages() {
406 return [
407 'action=query&list=search&srsearch=meaning'
408 => 'apihelp-query+search-example-simple',
409 'action=query&list=search&srwhat=text&srsearch=meaning'
410 => 'apihelp-query+search-example-text',
411 'action=query&generator=search&gsrsearch=meaning&prop=info'
412 => 'apihelp-query+search-example-generator',
413 ];
414 }
415
416 public function getHelpUrls() {
417 return 'https://www.mediawiki.org/wiki/API:Search';
418 }
419 }