Convert SearchResultSet to typical iteration
[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 $limit = $params['limit'];
146
147 foreach ( $matches as $result ) {
148 if ( ++$count > $limit ) {
149 // We've reached the one extra which shows that there are
150 // additional items to be had. Stop here...
151 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
152 break;
153 }
154
155 // Silently skip broken and missing titles
156 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
157 continue;
158 }
159
160 if ( $resultPageSet === null ) {
161 $vals = $this->getSearchResultData( $result, $prop, $terms );
162 if ( $vals ) {
163 // Add item to results and see whether it fits
164 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ], null, $vals );
165 if ( !$fit ) {
166 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
167 break;
168 }
169 }
170 } else {
171 $titles[] = $result->getTitle();
172 }
173 }
174
175 // Here we assume interwiki results do not count with
176 // regular search results. We may want to reconsider this
177 // if we ever return a lot of interwiki results or want pagination
178 // for them.
179 // Interwiki results inside main result set
180 $canAddInterwiki = (bool)$params['enablerewrites'] && ( $resultPageSet === null );
181 if ( $canAddInterwiki ) {
182 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'additional',
183 SearchResultSet::INLINE_RESULTS );
184 }
185
186 // Interwiki results outside main result set
187 if ( $interwiki && $resultPageSet === null ) {
188 $this->addInterwikiResults( $matches, $apiResult, $prop, $terms, 'interwiki',
189 SearchResultSet::SECONDARY_RESULTS );
190 }
191
192 if ( $resultPageSet === null ) {
193 $apiResult->addIndexedTagName( [
194 'query', $this->getModuleName()
195 ], 'p' );
196 } else {
197 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
198 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
199 $current['index'] = $new['index'];
200 }
201 return $current;
202 } );
203 $resultPageSet->populateFromTitles( $titles );
204 $offset = $params['offset'] + 1;
205 foreach ( $titles as $index => $title ) {
206 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
207 }
208 }
209 }
210
211 /**
212 * Assemble search result data.
213 * @param SearchResult $result Search result
214 * @param array $prop Props to extract (as keys)
215 * @param array $terms Terms list
216 * @return array|null Result data or null if result is broken in some way.
217 */
218 private function getSearchResultData( SearchResult $result, $prop, $terms ) {
219 // Silently skip broken and missing titles
220 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
221 return null;
222 }
223
224 $vals = [];
225
226 $title = $result->getTitle();
227 ApiQueryBase::addTitleInfo( $vals, $title );
228 $vals['pageid'] = $title->getArticleID();
229
230 if ( isset( $prop['size'] ) ) {
231 $vals['size'] = $result->getByteSize();
232 }
233 if ( isset( $prop['wordcount'] ) ) {
234 $vals['wordcount'] = $result->getWordCount();
235 }
236 if ( isset( $prop['snippet'] ) ) {
237 $vals['snippet'] = $result->getTextSnippet( $terms );
238 }
239 if ( isset( $prop['timestamp'] ) ) {
240 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
241 }
242 if ( isset( $prop['titlesnippet'] ) ) {
243 $vals['titlesnippet'] = $result->getTitleSnippet();
244 }
245 if ( isset( $prop['categorysnippet'] ) ) {
246 $vals['categorysnippet'] = $result->getCategorySnippet();
247 }
248 if ( !is_null( $result->getRedirectTitle() ) ) {
249 if ( isset( $prop['redirecttitle'] ) ) {
250 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
251 }
252 if ( isset( $prop['redirectsnippet'] ) ) {
253 $vals['redirectsnippet'] = $result->getRedirectSnippet();
254 }
255 }
256 if ( !is_null( $result->getSectionTitle() ) ) {
257 if ( isset( $prop['sectiontitle'] ) ) {
258 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
259 }
260 if ( isset( $prop['sectionsnippet'] ) ) {
261 $vals['sectionsnippet'] = $result->getSectionSnippet();
262 }
263 }
264 if ( isset( $prop['isfilematch'] ) ) {
265 $vals['isfilematch'] = $result->isFileMatch();
266 }
267
268 if ( isset( $prop['extensiondata'] ) ) {
269 $extra = $result->getExtensionData();
270 // Add augmented data to the result. The data would be organized as a map:
271 // augmentorName => data
272 if ( $extra ) {
273 $vals['extensiondata'] = ApiResult::addMetadataToResultVars( $extra );
274 }
275 }
276
277 return $vals;
278 }
279
280 /**
281 * Add interwiki results as a section in query results.
282 * @param SearchResultSet $matches
283 * @param ApiResult $apiResult
284 * @param array $prop Props to extract (as keys)
285 * @param array $terms Terms list
286 * @param string $section Section name where results would go
287 * @param int $type Interwiki result type
288 * @return int|null Number of total hits in the data or null if none was produced
289 */
290 private function addInterwikiResults(
291 SearchResultSet $matches, ApiResult $apiResult, $prop,
292 $terms, $section, $type
293 ) {
294 $totalhits = null;
295 if ( $matches->hasInterwikiResults( $type ) ) {
296 foreach ( $matches->getInterwikiResults( $type ) as $interwikiMatches ) {
297 // Include number of results if requested
298 $totalhits += $interwikiMatches->getTotalHits();
299
300 foreach ( $interwikiMatches as $result ) {
301 $title = $result->getTitle();
302 $vals = $this->getSearchResultData( $result, $prop, $terms );
303
304 $vals['namespace'] = $result->getInterwikiNamespaceText();
305 $vals['title'] = $title->getText();
306 $vals['url'] = $title->getFullURL();
307
308 // Add item to results and see whether it fits
309 $fit = $apiResult->addValue( [
310 'query',
311 $section . $this->getModuleName(),
312 $result->getInterwikiPrefix()
313 ], null, $vals );
314
315 if ( !$fit ) {
316 // We hit the limit. We can't really provide any meaningful
317 // pagination info so just bail out
318 break;
319 }
320 }
321 }
322 if ( $totalhits !== null ) {
323 $apiResult->addValue( [ 'query', $section . 'searchinfo' ], 'totalhits', $totalhits );
324 $apiResult->addIndexedTagName( [
325 'query', $section . $this->getModuleName()
326 ], 'p' );
327 }
328 }
329 return $totalhits;
330 }
331
332 public function getCacheMode( $params ) {
333 return 'public';
334 }
335
336 public function getAllowedParams() {
337 if ( $this->allowedParams !== null ) {
338 return $this->allowedParams;
339 }
340
341 $this->allowedParams = $this->buildCommonApiParams() + [
342 'what' => [
343 ApiBase::PARAM_TYPE => [
344 'title',
345 'text',
346 'nearmatch',
347 ]
348 ],
349 'info' => [
350 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
351 ApiBase::PARAM_TYPE => [
352 'totalhits',
353 'suggestion',
354 'rewrittenquery',
355 ],
356 ApiBase::PARAM_ISMULTI => true,
357 ],
358 'prop' => [
359 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
360 ApiBase::PARAM_TYPE => [
361 'size',
362 'wordcount',
363 'timestamp',
364 'snippet',
365 'titlesnippet',
366 'redirecttitle',
367 'redirectsnippet',
368 'sectiontitle',
369 'sectionsnippet',
370 'isfilematch',
371 'categorysnippet',
372 'score', // deprecated
373 'hasrelated', // deprecated
374 'extensiondata',
375 ],
376 ApiBase::PARAM_ISMULTI => true,
377 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
378 ApiBase::PARAM_DEPRECATED_VALUES => [
379 'score' => true,
380 'hasrelated' => true
381 ],
382 ],
383 'interwiki' => false,
384 'enablerewrites' => false,
385 ];
386
387 return $this->allowedParams;
388 }
389
390 public function getSearchProfileParams() {
391 return [
392 'qiprofile' => [
393 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
394 'help-message' => 'apihelp-query+search-param-qiprofile',
395 ],
396 ];
397 }
398
399 protected function getExamplesMessages() {
400 return [
401 'action=query&list=search&srsearch=meaning'
402 => 'apihelp-query+search-example-simple',
403 'action=query&list=search&srwhat=text&srsearch=meaning'
404 => 'apihelp-query+search-example-text',
405 'action=query&generator=search&gsrsearch=meaning&prop=info'
406 => 'apihelp-query+search-example-generator',
407 ];
408 }
409
410 public function getHelpUrls() {
411 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Search';
412 }
413 }