Enable supplying inline interwiki results
[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 /**
28 * Query module to perform full text search within wiki titles and content
29 *
30 * @ingroup API
31 */
32 class ApiQuerySearch extends ApiQueryGeneratorBase {
33 use SearchApi;
34
35 /** @var array list of api allowed params */
36 private $allowedParams;
37
38 public function __construct( ApiQuery $query, $moduleName ) {
39 parent::__construct( $query, $moduleName, 'sr' );
40 }
41
42 public function execute() {
43 $this->run();
44 }
45
46 public function executeGenerator( $resultPageSet ) {
47 $this->run( $resultPageSet );
48 }
49
50 /**
51 * @param ApiPageSet $resultPageSet
52 * @return void
53 */
54 private function run( $resultPageSet = null ) {
55 global $wgContLang;
56 $params = $this->extractRequestParams();
57
58 // Extract parameters
59 $query = $params['search'];
60 $what = $params['what'];
61 $interwiki = $params['interwiki'];
62 $searchInfo = array_flip( $params['info'] );
63 $prop = array_flip( $params['prop'] );
64
65 // Deprecated parameters
66 if ( isset( $prop['hasrelated'] ) ) {
67 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
68 $this->setWarning( 'srprop=hasrelated has been deprecated' );
69 }
70 if ( isset( $prop['score'] ) ) {
71 $this->logFeatureUsage( 'action=search&srprop=score' );
72 $this->setWarning( 'srprop=score has been deprecated' );
73 }
74
75 // Create search engine instance and set options
76 $search = $this->buildSearchEngine( $params );
77 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
78 $search->setFeatureData( 'interwiki', (bool)$interwiki );
79
80 $query = $search->transformSearchTerm( $query );
81 $query = $search->replacePrefixes( $query );
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->dieUsage( $status->getWikiText( false, false, 'en' ), 'search-error' );
126 }
127 } elseif ( is_null( $matches ) ) {
128 $this->dieUsage( "{$what} search is disabled", "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 = $wgContLang->convertForSearchResult( $matches->termMatches() );
157 $titles = [];
158 $count = 0;
159 $result = $matches->next();
160 $limit = $params['limit'];
161
162 while ( $result ) {
163 if ( ++$count > $limit ) {
164 // We've reached the one extra which shows that there are
165 // additional items to be had. Stop here...
166 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
167 break;
168 }
169
170 // Silently skip broken and missing titles
171 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
172 return null;
173 }
174
175 if ( $resultPageSet === null ) {
176 $vals = $this->getSearchResultData( $result, $prop, $terms );
177 if ( $vals ) {
178 // Add item to results and see whether it fits
179 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
180 if ( !$fit ) {
181 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
182 break;
183 }
184 }
185 } else {
186 $titles[] = $result->getTitle();
187 }
188
189 $result = $matches->next();
190 }
191
192 // Here we assume interwiki results do not count with
193 // regular search results. We may want to reconsider this
194 // if we ever return a lot of interwiki results or want pagination
195 // for them.
196 // Interwiki results inside main result set
197 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
198 if ( $canAddInterwiki ) {
199 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
200 SearchResultSet::INLINE_RESULTS );
201 }
202
203 // Interwiki results outside main result set
204 if ( $interwiki && $resultPageSet === null ) {
205 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
206 SearchResultSet::SECONDARY_RESULTS );
207 }
208
209 if ( $resultPageSet === null ) {
210 $apiResult->addIndexedTagName( [
211 'query', $this->getModuleName()
212 ], 'p' );
213 } else {
214 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
215 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
216 $current['index'] = $new['index'];
217 }
218 return $current;
219 } );
220 $resultPageSet->populateFromTitles( $titles );
221 $offset = $params['offset'] + 1;
222 foreach ( $titles as $index => $title ) {
223 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
224 }
225 }
226 }
227
228 /**
229 * Assemble search result data.
230 * @param SearchResult $result Search result
231 * @param array $prop Props to extract (as keys)
232 * @param array $terms Terms list
233 * @return array|null Result data or null if result is broken in some way.
234 */
235 private function getSearchResultData( SearchResult $result, $prop, $terms ) {
236 // Silently skip broken and missing titles
237 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
238 return null;
239 }
240
241 $vals = [];
242
243 $title = $result->getTitle();
244 ApiQueryBase::addTitleInfo( $vals, $title );
245
246 if ( isset( $prop['size'] ) ) {
247 $vals['size'] = $result->getByteSize();
248 }
249 if ( isset( $prop['wordcount'] ) ) {
250 $vals['wordcount'] = $result->getWordCount();
251 }
252 if ( isset( $prop['snippet'] ) ) {
253 $vals['snippet'] = $result->getTextSnippet( $terms );
254 }
255 if ( isset( $prop['timestamp'] ) ) {
256 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
257 }
258 if ( isset( $prop['titlesnippet'] ) ) {
259 $vals['titlesnippet'] = $result->getTitleSnippet();
260 }
261 if ( isset( $prop['categorysnippet'] ) ) {
262 $vals['categorysnippet'] = $result->getCategorySnippet();
263 }
264 if ( !is_null( $result->getRedirectTitle() ) ) {
265 if ( isset( $prop['redirecttitle'] ) ) {
266 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
267 }
268 if ( isset( $prop['redirectsnippet'] ) ) {
269 $vals['redirectsnippet'] = $result->getRedirectSnippet();
270 }
271 }
272 if ( !is_null( $result->getSectionTitle() ) ) {
273 if ( isset( $prop['sectiontitle'] ) ) {
274 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
275 }
276 if ( isset( $prop['sectionsnippet'] ) ) {
277 $vals['sectionsnippet'] = $result->getSectionSnippet();
278 }
279 }
280 if ( isset( $prop['isfilematch'] ) ) {
281 $vals['isfilematch'] = $result->isFileMatch();
282 }
283 return $vals;
284 }
285
286 /**
287 * Add interwiki results as a section in query results.
288 * @param SearchResultSet $matches
289 * @param ApiResult $apiResult
290 * @param array $prop Props to extract (as keys)
291 * @param array $terms Terms list
292 * @param string $section Section name where results would go
293 * @param int $type Interwiki result type
294 * @return int|null Number of total hits in the data or null if none was produced
295 */
296 private function addInterwikiResults(
297 SearchResultSet $matches, ApiResult $apiResult, $prop,
298 $terms, $section, $type
299 ) {
300 $totalhits = null;
301 if ( $matches->hasInterwikiResults( $type ) ) {
302 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
303 // Include number of results if requested
304 $totalhits += $interwikiMatches->getTotalHits();
305
306 $result = $interwikiMatches->next();
307 while ( $result ) {
308 $title = $result->getTitle();
309 $vals = $this->getSearchResultData( $result, $prop, $terms );
310
311 $vals['namespace'] = $result->getInterwikiNamespaceText();
312 $vals['title'] = $title->getText();
313 $vals['url'] = $title->getFullURL();
314
315 // Add item to results and see whether it fits
316 $fit = $apiResult->addValue( [
317 'query',
318 $section . $this->getModuleName(),
319 $result->getInterwikiPrefix()
320 ], null, $vals );
321
322 if ( !$fit ) {
323 // We hit the limit. We can't really provide any meaningful
324 // pagination info so just bail out
325 break;
326 }
327
328 $result = $interwikiMatches->next();
329 }
330 }
331 if ( $totalhits !== null ) {
332 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
333 $apiResult->addIndexedTagName( [
334 'query', $section . $this->getModuleName()
335 ], 'p' );
336 }
337 }
338 return $totalhits;
339 }
340
341 public function getCacheMode( $params ) {
342 return 'public';
343 }
344
345 public function getAllowedParams() {
346 if ( $this->allowedParams !== null ) {
347 return $this->allowedParams;
348 }
349
350 $this->allowedParams = $this->buildCommonApiParams() + [
351 'what' => [
352 ApiBase::PARAM_TYPE => [
353 'title',
354 'text',
355 'nearmatch',
356 ]
357 ],
358 'info' => [
359 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
360 ApiBase::PARAM_TYPE => [
361 'totalhits',
362 'suggestion',
363 'rewrittenquery',
364 ],
365 ApiBase::PARAM_ISMULTI => true,
366 ],
367 'prop' => [
368 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
369 ApiBase::PARAM_TYPE => [
370 'size',
371 'wordcount',
372 'timestamp',
373 'snippet',
374 'titlesnippet',
375 'redirecttitle',
376 'redirectsnippet',
377 'sectiontitle',
378 'sectionsnippet',
379 'isfilematch',
380 'categorysnippet',
381 'score', // deprecated
382 'hasrelated', // deprecated
383 ],
384 ApiBase::PARAM_ISMULTI => true,
385 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
386 ],
387 'interwiki' => false,
388 'enablerewrites' => false,
389 ];
390
391 return $this->allowedParams;
392 }
393
394 public function getSearchProfileParams() {
395 return [
396 'qiprofile' => [
397 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
398 'help-message' => 'apihelp-query+search-param-qiprofile',
399 ],
400 ];
401 }
402
403 protected function getExamplesMessages() {
404 return [
405 'action=query&list=search&srsearch=meaning'
406 => 'apihelp-query+search-example-simple',
407 'action=query&list=search&srwhat=text&srsearch=meaning'
408 => 'apihelp-query+search-example-text',
409 'action=query&generator=search&gsrsearch=meaning&prop=info'
410 => 'apihelp-query+search-example-generator',
411 ];
412 }
413
414 public function getHelpUrls() {
415 return 'https://www.mediawiki.org/wiki/API:Search';
416 }
417 }