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