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