Merge "ApiUpload: Better handle ApiMessage errors from UploadVerifyFile hook"
[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 use MediaWiki\MediaWikiServices;
28
29 /**
30 * Query module to perform full text search within wiki titles and content
31 *
32 * @ingroup API
33 */
34 class ApiQuerySearch extends ApiQueryGeneratorBase {
35 use SearchApi;
36
37 /** @var array list of api allowed params */
38 private $allowedParams;
39
40 /**
41 * When $wgSearchType is null, $wgSearchAlternatives[0] is null. Null isn't
42 * a valid option for an array for PARAM_TYPE, so we'll use a fake name
43 * that can't possibly be a class name and describes what the null behavior
44 * does
45 */
46 const BACKEND_NULL_PARAM = 'database-backed';
47
48 public function __construct( ApiQuery $query, $moduleName ) {
49 parent::__construct( $query, $moduleName, 'sr' );
50 }
51
52 public function execute() {
53 $this->run();
54 }
55
56 public function executeGenerator( $resultPageSet ) {
57 $this->run( $resultPageSet );
58 }
59
60 /**
61 * @param ApiPageSet $resultPageSet
62 * @return void
63 */
64 private function run( $resultPageSet = null ) {
65 global $wgContLang;
66 $params = $this->extractRequestParams();
67
68 if ( isset( $params['backend'] ) && $params['backend'] == self::BACKEND_NULL_PARAM ) {
69 unset( $params['backend'] );
70 }
71
72 // Extract parameters
73 $query = $params['search'];
74 $what = $params['what'];
75 $interwiki = $params['interwiki'];
76 $searchInfo = array_flip( $params['info'] );
77 $prop = array_flip( $params['prop'] );
78
79 // Deprecated parameters
80 if ( isset( $prop['hasrelated'] ) ) {
81 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
82 $this->setWarning( 'srprop=hasrelated has been deprecated' );
83 }
84 if ( isset( $prop['score'] ) ) {
85 $this->logFeatureUsage( 'action=search&srprop=score' );
86 $this->setWarning( 'srprop=score has been deprecated' );
87 }
88
89 // Create search engine instance and set options
90 $search = $this->buildSearchEngine( $params );
91 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
92
93 $query = $search->transformSearchTerm( $query );
94 $query = $search->replacePrefixes( $query );
95
96 // Perform the actual search
97 if ( $what == 'text' ) {
98 $matches = $search->searchText( $query );
99 } elseif ( $what == 'title' ) {
100 $matches = $search->searchTitle( $query );
101 } elseif ( $what == 'nearmatch' ) {
102 // near matches must receive the user input as provided, otherwise
103 // the near matches within namespaces are lost.
104 $matches = $search->getNearMatcher( $this->getConfig() )
105 ->getNearMatchResultSet( $params['search'] );
106 } else {
107 // We default to title searches; this is a terrible legacy
108 // of the way we initially set up the MySQL fulltext-based
109 // search engine with separate title and text fields.
110 // In the future, the default should be for a combined index.
111 $what = 'title';
112 $matches = $search->searchTitle( $query );
113
114 // Not all search engines support a separate title search,
115 // for instance the Lucene-based engine we use on Wikipedia.
116 // In this case, fall back to full-text search (which will
117 // include titles in it!)
118 if ( is_null( $matches ) ) {
119 $what = 'text';
120 $matches = $search->searchText( $query );
121 }
122 }
123 if ( is_null( $matches ) ) {
124 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
125 } elseif ( $matches instanceof Status && !$matches->isGood() ) {
126 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
127 }
128
129 if ( $resultPageSet === null ) {
130 $apiResult = $this->getResult();
131 // Add search meta data to result
132 if ( isset( $searchInfo['totalhits'] ) ) {
133 $totalhits = $matches->getTotalHits();
134 if ( $totalhits !== null ) {
135 $apiResult->addValue( [ 'query', 'searchinfo' ],
136 'totalhits', $totalhits );
137 }
138 }
139 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
140 $apiResult->addValue( [ 'query', 'searchinfo' ],
141 'suggestion', $matches->getSuggestionQuery() );
142 $apiResult->addValue( [ 'query', 'searchinfo' ],
143 'suggestionsnippet', $matches->getSuggestionSnippet() );
144 }
145 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
146 $apiResult->addValue( [ 'query', 'searchinfo' ],
147 'rewrittenquery', $matches->getQueryAfterRewrite() );
148 $apiResult->addValue( [ 'query', 'searchinfo' ],
149 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
150 }
151 }
152
153 // Add the search results to the result
154 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
155 $titles = [];
156 $count = 0;
157 $result = $matches->next();
158 $limit = $params['limit'];
159
160 while ( $result ) {
161 if ( ++$count > $limit ) {
162 // We've reached the one extra which shows that there are
163 // additional items to be had. Stop here...
164 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
165 break;
166 }
167
168 // Silently skip broken and missing titles
169 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
170 $result = $matches->next();
171 continue;
172 }
173
174 $title = $result->getTitle();
175 if ( $resultPageSet === null ) {
176 $vals = [];
177 ApiQueryBase::addTitleInfo( $vals, $title );
178
179 if ( isset( $prop['snippet'] ) ) {
180 $vals['snippet'] = $result->getTextSnippet( $terms );
181 }
182 if ( isset( $prop['size'] ) ) {
183 $vals['size'] = $result->getByteSize();
184 }
185 if ( isset( $prop['wordcount'] ) ) {
186 $vals['wordcount'] = $result->getWordCount();
187 }
188 if ( isset( $prop['timestamp'] ) ) {
189 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
190 }
191 if ( isset( $prop['titlesnippet'] ) ) {
192 $vals['titlesnippet'] = $result->getTitleSnippet();
193 }
194 if ( isset( $prop['categorysnippet'] ) ) {
195 $vals['categorysnippet'] = $result->getCategorySnippet();
196 }
197 if ( !is_null( $result->getRedirectTitle() ) ) {
198 if ( isset( $prop['redirecttitle'] ) ) {
199 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
200 }
201 if ( isset( $prop['redirectsnippet'] ) ) {
202 $vals['redirectsnippet'] = $result->getRedirectSnippet();
203 }
204 }
205 if ( !is_null( $result->getSectionTitle() ) ) {
206 if ( isset( $prop['sectiontitle'] ) ) {
207 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
208 }
209 if ( isset( $prop['sectionsnippet'] ) ) {
210 $vals['sectionsnippet'] = $result->getSectionSnippet();
211 }
212 }
213 if ( isset( $prop['isfilematch'] ) ) {
214 $vals['isfilematch'] = $result->isFileMatch();
215 }
216
217 // Add item to results and see whether it fits
218 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
219 null, $vals );
220 if ( !$fit ) {
221 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
222 break;
223 }
224 } else {
225 $titles[] = $title;
226 }
227
228 $result = $matches->next();
229 }
230
231 $hasInterwikiResults = false;
232 $totalhits = null;
233 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
234 foreach ( $matches->getInterwikiResults() as $interwikiMatches ) {
235 $hasInterwikiResults = true;
236
237 // Include number of results if requested
238 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
239 $totalhits += $interwikiMatches->getTotalHits();
240 }
241
242 $result = $interwikiMatches->next();
243 while ( $result ) {
244 $title = $result->getTitle();
245
246 if ( $resultPageSet === null ) {
247 $vals = [
248 'namespace' => $result->getInterwikiNamespaceText(),
249 'title' => $title->getText(),
250 'url' => $title->getFullUrl(),
251 ];
252
253 // Add item to results and see whether it fits
254 $fit = $apiResult->addValue(
255 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
256 null,
257 $vals
258 );
259
260 if ( !$fit ) {
261 // We hit the limit. We can't really provide any meaningful
262 // pagination info so just bail out
263 break;
264 }
265 } else {
266 $titles[] = $title;
267 }
268
269 $result = $interwikiMatches->next();
270 }
271 }
272 if ( $totalhits !== null ) {
273 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
274 'totalhits', $totalhits );
275 }
276 }
277
278 if ( $resultPageSet === null ) {
279 $apiResult->addIndexedTagName( [
280 'query', $this->getModuleName()
281 ], 'p' );
282 if ( $hasInterwikiResults ) {
283 $apiResult->addIndexedTagName( [
284 'query', 'interwiki' . $this->getModuleName()
285 ], 'p' );
286 }
287 } else {
288 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
289 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
290 $current['index'] = $new['index'];
291 }
292 return $current;
293 } );
294 $resultPageSet->populateFromTitles( $titles );
295 $offset = $params['offset'] + 1;
296 foreach ( $titles as $index => $title ) {
297 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
298 }
299 }
300 }
301
302 public function getCacheMode( $params ) {
303 return 'public';
304 }
305
306 public function getAllowedParams() {
307 if ( $this->allowedParams !== null ) {
308 return $this->allowedParams;
309 }
310
311 $this->allowedParams = [
312 'search' => [
313 ApiBase::PARAM_TYPE => 'string',
314 ApiBase::PARAM_REQUIRED => true
315 ],
316 'namespace' => [
317 ApiBase::PARAM_DFLT => NS_MAIN,
318 ApiBase::PARAM_TYPE => 'namespace',
319 ApiBase::PARAM_ISMULTI => true,
320 ],
321 'what' => [
322 ApiBase::PARAM_TYPE => [
323 'title',
324 'text',
325 'nearmatch',
326 ]
327 ],
328 'info' => [
329 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
330 ApiBase::PARAM_TYPE => [
331 'totalhits',
332 'suggestion',
333 'rewrittenquery',
334 ],
335 ApiBase::PARAM_ISMULTI => true,
336 ],
337 'prop' => [
338 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
339 ApiBase::PARAM_TYPE => [
340 'size',
341 'wordcount',
342 'timestamp',
343 'snippet',
344 'titlesnippet',
345 'redirecttitle',
346 'redirectsnippet',
347 'sectiontitle',
348 'sectionsnippet',
349 'isfilematch',
350 'categorysnippet',
351 'score', // deprecated
352 'hasrelated', // deprecated
353 ],
354 ApiBase::PARAM_ISMULTI => true,
355 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
356 ],
357 'offset' => [
358 ApiBase::PARAM_DFLT => 0,
359 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
360 ],
361 'limit' => [
362 ApiBase::PARAM_DFLT => 10,
363 ApiBase::PARAM_TYPE => 'limit',
364 ApiBase::PARAM_MIN => 1,
365 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
366 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
367 ],
368 'interwiki' => false,
369 'enablerewrites' => false,
370 ];
371
372 $searchConfig = MediaWikiServices::getInstance()->getSearchEngineConfig();
373 $alternatives = $searchConfig->getSearchTypes();
374 if ( count( $alternatives ) > 1 ) {
375 if ( $alternatives[0] === null ) {
376 $alternatives[0] = self::BACKEND_NULL_PARAM;
377 }
378 $this->allowedParams['backend'] = [
379 ApiBase::PARAM_DFLT => $searchConfig->getSearchType(),
380 ApiBase::PARAM_TYPE => $alternatives,
381 ];
382 // @todo: support profile selection when multiple
383 // backends are available. The solution could be to
384 // merge all possible profiles and let ApiBase
385 // subclasses do the check. Making ApiHelp and ApiSandbox
386 // comprehensive might be more difficult.
387 } else {
388 $profileParam = $this->buildProfileApiParam( SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
389 'apihelp-query+search-param-qiprofile' );
390 if ( $profileParam ) {
391 $this->allowedParams['qiprofile'] = $profileParam;
392 }
393 }
394
395 return $this->allowedParams;
396 }
397
398 public function getSearchProfileParams() {
399 if ( isset( $this->getAllowedParams()['qiprofile'] ) ) {
400 return [ SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE => 'qiprofile' ];
401 }
402 return [];
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 }