Push common search api parameters into SearchApi class
[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 public function __construct( ApiQuery $query, $moduleName ) {
41 parent::__construct( $query, $moduleName, 'sr' );
42 }
43
44 public function execute() {
45 $this->run();
46 }
47
48 public function executeGenerator( $resultPageSet ) {
49 $this->run( $resultPageSet );
50 }
51
52 /**
53 * @param ApiPageSet $resultPageSet
54 * @return void
55 */
56 private function run( $resultPageSet = null ) {
57 global $wgContLang;
58 $params = $this->extractRequestParams();
59
60 // Extract parameters
61 $query = $params['search'];
62 $what = $params['what'];
63 $interwiki = $params['interwiki'];
64 $searchInfo = array_flip( $params['info'] );
65 $prop = array_flip( $params['prop'] );
66
67 // Deprecated parameters
68 if ( isset( $prop['hasrelated'] ) ) {
69 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
70 $this->setWarning( 'srprop=hasrelated has been deprecated' );
71 }
72 if ( isset( $prop['score'] ) ) {
73 $this->logFeatureUsage( 'action=search&srprop=score' );
74 $this->setWarning( 'srprop=score has been deprecated' );
75 }
76
77 // Create search engine instance and set options
78 $search = $this->buildSearchEngine( $params );
79 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
80
81 $query = $search->transformSearchTerm( $query );
82 $query = $search->replacePrefixes( $query );
83
84 // Perform the actual search
85 if ( $what == 'text' ) {
86 $matches = $search->searchText( $query );
87 } elseif ( $what == 'title' ) {
88 $matches = $search->searchTitle( $query );
89 } elseif ( $what == 'nearmatch' ) {
90 // near matches must receive the user input as provided, otherwise
91 // the near matches within namespaces are lost.
92 $matches = $search->getNearMatcher( $this->getConfig() )
93 ->getNearMatchResultSet( $params['search'] );
94 } else {
95 // We default to title searches; this is a terrible legacy
96 // of the way we initially set up the MySQL fulltext-based
97 // search engine with separate title and text fields.
98 // In the future, the default should be for a combined index.
99 $what = 'title';
100 $matches = $search->searchTitle( $query );
101
102 // Not all search engines support a separate title search,
103 // for instance the Lucene-based engine we use on Wikipedia.
104 // In this case, fall back to full-text search (which will
105 // include titles in it!)
106 if ( is_null( $matches ) ) {
107 $what = 'text';
108 $matches = $search->searchText( $query );
109 }
110 }
111 if ( is_null( $matches ) ) {
112 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
113 } elseif ( $matches instanceof Status && !$matches->isGood() ) {
114 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
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 $title = $result->getTitle();
163 if ( $resultPageSet === null ) {
164 $vals = [];
165 ApiQueryBase::addTitleInfo( $vals, $title );
166
167 if ( isset( $prop['snippet'] ) ) {
168 $vals['snippet'] = $result->getTextSnippet( $terms );
169 }
170 if ( isset( $prop['size'] ) ) {
171 $vals['size'] = $result->getByteSize();
172 }
173 if ( isset( $prop['wordcount'] ) ) {
174 $vals['wordcount'] = $result->getWordCount();
175 }
176 if ( isset( $prop['timestamp'] ) ) {
177 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
178 }
179 if ( isset( $prop['titlesnippet'] ) ) {
180 $vals['titlesnippet'] = $result->getTitleSnippet();
181 }
182 if ( isset( $prop['categorysnippet'] ) ) {
183 $vals['categorysnippet'] = $result->getCategorySnippet();
184 }
185 if ( !is_null( $result->getRedirectTitle() ) ) {
186 if ( isset( $prop['redirecttitle'] ) ) {
187 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
188 }
189 if ( isset( $prop['redirectsnippet'] ) ) {
190 $vals['redirectsnippet'] = $result->getRedirectSnippet();
191 }
192 }
193 if ( !is_null( $result->getSectionTitle() ) ) {
194 if ( isset( $prop['sectiontitle'] ) ) {
195 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
196 }
197 if ( isset( $prop['sectionsnippet'] ) ) {
198 $vals['sectionsnippet'] = $result->getSectionSnippet();
199 }
200 }
201 if ( isset( $prop['isfilematch'] ) ) {
202 $vals['isfilematch'] = $result->isFileMatch();
203 }
204
205 // Add item to results and see whether it fits
206 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
207 null, $vals );
208 if ( !$fit ) {
209 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
210 break;
211 }
212 } else {
213 $titles[] = $title;
214 }
215
216 $result = $matches->next();
217 }
218
219 $hasInterwikiResults = false;
220 $totalhits = null;
221 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
222 foreach ( $matches->getInterwikiResults() as $matches ) {
223 $matches = $matches->getInterwikiResults();
224 $hasInterwikiResults = true;
225
226 // Include number of results if requested
227 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
228 $totalhits += $matches->getTotalHits();
229 }
230
231 $result = $matches->next();
232 while ( $result ) {
233 $title = $result->getTitle();
234
235 if ( $resultPageSet === null ) {
236 $vals = [
237 'namespace' => $result->getInterwikiNamespaceText(),
238 'title' => $title->getText(),
239 'url' => $title->getFullUrl(),
240 ];
241
242 // Add item to results and see whether it fits
243 $fit = $apiResult->addValue(
244 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
245 null,
246 $vals
247 );
248
249 if ( !$fit ) {
250 // We hit the limit. We can't really provide any meaningful
251 // pagination info so just bail out
252 break;
253 }
254 } else {
255 $titles[] = $title;
256 }
257
258 $result = $matches->next();
259 }
260 }
261 if ( $totalhits !== null ) {
262 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
263 'totalhits', $totalhits );
264 }
265 }
266
267 if ( $resultPageSet === null ) {
268 $apiResult->addIndexedTagName( [
269 'query', $this->getModuleName()
270 ], 'p' );
271 if ( $hasInterwikiResults ) {
272 $apiResult->addIndexedTagName( [
273 'query', 'interwiki' . $this->getModuleName()
274 ], 'p' );
275 }
276 } else {
277 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
278 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
279 $current['index'] = $new['index'];
280 }
281 return $current;
282 } );
283 $resultPageSet->populateFromTitles( $titles );
284 $offset = $params['offset'] + 1;
285 foreach ( $titles as $index => $title ) {
286 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
287 }
288 }
289 }
290
291 public function getCacheMode( $params ) {
292 return 'public';
293 }
294
295 public function getAllowedParams() {
296 if ( $this->allowedParams !== null ) {
297 return $this->allowedParams;
298 }
299
300 $this->allowedParams = $this->buildCommonApiParams() + [
301 'what' => [
302 ApiBase::PARAM_TYPE => [
303 'title',
304 'text',
305 'nearmatch',
306 ]
307 ],
308 'info' => [
309 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
310 ApiBase::PARAM_TYPE => [
311 'totalhits',
312 'suggestion',
313 'rewrittenquery',
314 ],
315 ApiBase::PARAM_ISMULTI => true,
316 ],
317 'prop' => [
318 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
319 ApiBase::PARAM_TYPE => [
320 'size',
321 'wordcount',
322 'timestamp',
323 'snippet',
324 'titlesnippet',
325 'redirecttitle',
326 'redirectsnippet',
327 'sectiontitle',
328 'sectionsnippet',
329 'isfilematch',
330 'categorysnippet',
331 'score', // deprecated
332 'hasrelated', // deprecated
333 ],
334 ApiBase::PARAM_ISMULTI => true,
335 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
336 ],
337 'interwiki' => false,
338 'enablerewrites' => false,
339 ];
340
341 return $this->allowedParams;
342 }
343
344 public function getSearchProfileParams() {
345 return [
346 'qiprofile' => [
347 'profile-type' => SearchEngine::FT_QUERY_INDEP_PROFILE_TYPE,
348 'help-message' => 'apihelp-query+search-param-qiprofile',
349 ],
350 ];
351 }
352
353 protected function getExamplesMessages() {
354 return [
355 'action=query&list=search&srsearch=meaning'
356 => 'apihelp-query+search-example-simple',
357 'action=query&list=search&srwhat=text&srsearch=meaning'
358 => 'apihelp-query+search-example-text',
359 'action=query&generator=search&gsrsearch=meaning&prop=info'
360 => 'apihelp-query+search-example-generator',
361 ];
362 }
363
364 public function getHelpUrls() {
365 return 'https://www.mediawiki.org/wiki/API:Search';
366 }
367 }