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