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