Merge "i18n: Provide new "publish" strings for extra translator time"
[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
36 /**
37 * When $wgSearchType is null, $wgSearchAlternatives[0] is null. Null isn't
38 * a valid option for an array for PARAM_TYPE, so we'll use a fake name
39 * that can't possibly be a class name and describes what the null behavior
40 * does
41 */
42 const BACKEND_NULL_PARAM = 'database-backed';
43
44 public function __construct( ApiQuery $query, $moduleName ) {
45 parent::__construct( $query, $moduleName, 'sr' );
46 }
47
48 public function execute() {
49 $this->run();
50 }
51
52 public function executeGenerator( $resultPageSet ) {
53 $this->run( $resultPageSet );
54 }
55
56 /**
57 * @param ApiPageSet $resultPageSet
58 * @return void
59 */
60 private function run( $resultPageSet = null ) {
61 global $wgContLang;
62 $params = $this->extractRequestParams();
63
64 // Extract parameters
65 $limit = $params['limit'];
66 $query = $params['search'];
67 $what = $params['what'];
68 $interwiki = $params['interwiki'];
69 $searchInfo = array_flip( $params['info'] );
70 $prop = array_flip( $params['prop'] );
71
72 // Deprecated parameters
73 if ( isset( $prop['hasrelated'] ) ) {
74 $this->logFeatureUsage( 'action=search&srprop=hasrelated' );
75 $this->setWarning( 'srprop=hasrelated has been deprecated' );
76 }
77 if ( isset( $prop['score'] ) ) {
78 $this->logFeatureUsage( 'action=search&srprop=score' );
79 $this->setWarning( 'srprop=score has been deprecated' );
80 }
81
82 // Create search engine instance and set options
83 $type = isset( $params['backend'] ) && $params['backend'] != self::BACKEND_NULL_PARAM ?
84 $params['backend'] : null;
85 $search = MediaWikiServices::getInstance()->getSearchEngineFactory()->create( $type );
86 $search->setLimitOffset( $limit + 1, $params['offset'] );
87 $search->setNamespaces( $params['namespace'] );
88 $search->setFeatureData( 'rewrite', (bool)$params['enablerewrites'] );
89
90 $query = $search->transformSearchTerm( $query );
91 $query = $search->replacePrefixes( $query );
92
93 // Perform the actual search
94 if ( $what == 'text' ) {
95 $matches = $search->searchText( $query );
96 } elseif ( $what == 'title' ) {
97 $matches = $search->searchTitle( $query );
98 } elseif ( $what == 'nearmatch' ) {
99 // near matches must receive the user input as provided, otherwise
100 // the near matches within namespaces are lost.
101 $matches = $search->getNearMatcher( $this->getConfig() )
102 ->getNearMatchResultSet( $params['search'] );
103 } else {
104 // We default to title searches; this is a terrible legacy
105 // of the way we initially set up the MySQL fulltext-based
106 // search engine with separate title and text fields.
107 // In the future, the default should be for a combined index.
108 $what = 'title';
109 $matches = $search->searchTitle( $query );
110
111 // Not all search engines support a separate title search,
112 // for instance the Lucene-based engine we use on Wikipedia.
113 // In this case, fall back to full-text search (which will
114 // include titles in it!)
115 if ( is_null( $matches ) ) {
116 $what = 'text';
117 $matches = $search->searchText( $query );
118 }
119 }
120 if ( is_null( $matches ) ) {
121 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
122 } elseif ( $matches instanceof Status && !$matches->isGood() ) {
123 $this->dieUsage( $matches->getWikiText( false, false, 'en' ), 'search-error' );
124 }
125
126 if ( $resultPageSet === null ) {
127 $apiResult = $this->getResult();
128 // Add search meta data to result
129 if ( isset( $searchInfo['totalhits'] ) ) {
130 $totalhits = $matches->getTotalHits();
131 if ( $totalhits !== null ) {
132 $apiResult->addValue( [ 'query', 'searchinfo' ],
133 'totalhits', $totalhits );
134 }
135 }
136 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
137 $apiResult->addValue( [ 'query', 'searchinfo' ],
138 'suggestion', $matches->getSuggestionQuery() );
139 $apiResult->addValue( [ 'query', 'searchinfo' ],
140 'suggestionsnippet', $matches->getSuggestionSnippet() );
141 }
142 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
143 $apiResult->addValue( [ 'query', 'searchinfo' ],
144 'rewrittenquery', $matches->getQueryAfterRewrite() );
145 $apiResult->addValue( [ 'query', 'searchinfo' ],
146 'rewrittenquerysnippet', $matches->getQueryAfterRewriteSnippet() );
147 }
148 }
149
150 // Add the search results to the result
151 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
152 $titles = [];
153 $count = 0;
154 $result = $matches->next();
155
156 while ( $result ) {
157 if ( ++$count > $limit ) {
158 // We've reached the one extra which shows that there are
159 // additional items to be had. Stop here...
160 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
161 break;
162 }
163
164 // Silently skip broken and missing titles
165 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
166 $result = $matches->next();
167 continue;
168 }
169
170 $title = $result->getTitle();
171 if ( $resultPageSet === null ) {
172 $vals = [];
173 ApiQueryBase::addTitleInfo( $vals, $title );
174
175 if ( isset( $prop['snippet'] ) ) {
176 $vals['snippet'] = $result->getTextSnippet( $terms );
177 }
178 if ( isset( $prop['size'] ) ) {
179 $vals['size'] = $result->getByteSize();
180 }
181 if ( isset( $prop['wordcount'] ) ) {
182 $vals['wordcount'] = $result->getWordCount();
183 }
184 if ( isset( $prop['timestamp'] ) ) {
185 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
186 }
187 if ( isset( $prop['titlesnippet'] ) ) {
188 $vals['titlesnippet'] = $result->getTitleSnippet();
189 }
190 if ( isset( $prop['categorysnippet'] ) ) {
191 $vals['categorysnippet'] = $result->getCategorySnippet();
192 }
193 if ( !is_null( $result->getRedirectTitle() ) ) {
194 if ( isset( $prop['redirecttitle'] ) ) {
195 $vals['redirecttitle'] = $result->getRedirectTitle()->getPrefixedText();
196 }
197 if ( isset( $prop['redirectsnippet'] ) ) {
198 $vals['redirectsnippet'] = $result->getRedirectSnippet();
199 }
200 }
201 if ( !is_null( $result->getSectionTitle() ) ) {
202 if ( isset( $prop['sectiontitle'] ) ) {
203 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
204 }
205 if ( isset( $prop['sectionsnippet'] ) ) {
206 $vals['sectionsnippet'] = $result->getSectionSnippet();
207 }
208 }
209 if ( isset( $prop['isfilematch'] ) ) {
210 $vals['isfilematch'] = $result->isFileMatch();
211 }
212
213 // Add item to results and see whether it fits
214 $fit = $apiResult->addValue( [ 'query', $this->getModuleName() ],
215 null, $vals );
216 if ( !$fit ) {
217 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
218 break;
219 }
220 } else {
221 $titles[] = $title;
222 }
223
224 $result = $matches->next();
225 }
226
227 $hasInterwikiResults = false;
228 $totalhits = null;
229 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
230 foreach ( $matches->getInterwikiResults() as $matches ) {
231 $matches = $matches->getInterwikiResults();
232 $hasInterwikiResults = true;
233
234 // Include number of results if requested
235 if ( $resultPageSet === null && isset( $searchInfo['totalhits'] ) ) {
236 $totalhits += $matches->getTotalHits();
237 }
238
239 $result = $matches->next();
240 while ( $result ) {
241 $title = $result->getTitle();
242
243 if ( $resultPageSet === null ) {
244 $vals = [
245 'namespace' => $result->getInterwikiNamespaceText(),
246 'title' => $title->getText(),
247 'url' => $title->getFullUrl(),
248 ];
249
250 // Add item to results and see whether it fits
251 $fit = $apiResult->addValue(
252 [ 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ],
253 null,
254 $vals
255 );
256
257 if ( !$fit ) {
258 // We hit the limit. We can't really provide any meaningful
259 // pagination info so just bail out
260 break;
261 }
262 } else {
263 $titles[] = $title;
264 }
265
266 $result = $matches->next();
267 }
268 }
269 if ( $totalhits !== null ) {
270 $apiResult->addValue( [ 'query', 'interwikisearchinfo' ],
271 'totalhits', $totalhits );
272 }
273 }
274
275 if ( $resultPageSet === null ) {
276 $apiResult->addIndexedTagName( [
277 'query', $this->getModuleName()
278 ], 'p' );
279 if ( $hasInterwikiResults ) {
280 $apiResult->addIndexedTagName( [
281 'query', 'interwiki' . $this->getModuleName()
282 ], 'p' );
283 }
284 } else {
285 $resultPageSet->setRedirectMergePolicy( function ( $current, $new ) {
286 if ( !isset( $current['index'] ) || $new['index'] < $current['index'] ) {
287 $current['index'] = $new['index'];
288 }
289 return $current;
290 } );
291 $resultPageSet->populateFromTitles( $titles );
292 $offset = $params['offset'] + 1;
293 foreach ( $titles as $index => $title ) {
294 $resultPageSet->setGeneratorData( $title, [ 'index' => $index + $offset ] );
295 }
296 }
297 }
298
299 public function getCacheMode( $params ) {
300 return 'public';
301 }
302
303 public function getAllowedParams() {
304 $params = [
305 'search' => [
306 ApiBase::PARAM_TYPE => 'string',
307 ApiBase::PARAM_REQUIRED => true
308 ],
309 'namespace' => [
310 ApiBase::PARAM_DFLT => NS_MAIN,
311 ApiBase::PARAM_TYPE => 'namespace',
312 ApiBase::PARAM_ISMULTI => true,
313 ],
314 'what' => [
315 ApiBase::PARAM_TYPE => [
316 'title',
317 'text',
318 'nearmatch',
319 ]
320 ],
321 'info' => [
322 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
323 ApiBase::PARAM_TYPE => [
324 'totalhits',
325 'suggestion',
326 'rewrittenquery',
327 ],
328 ApiBase::PARAM_ISMULTI => true,
329 ],
330 'prop' => [
331 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
332 ApiBase::PARAM_TYPE => [
333 'size',
334 'wordcount',
335 'timestamp',
336 'snippet',
337 'titlesnippet',
338 'redirecttitle',
339 'redirectsnippet',
340 'sectiontitle',
341 'sectionsnippet',
342 'isfilematch',
343 'categorysnippet',
344 'score', // deprecated
345 'hasrelated', // deprecated
346 ],
347 ApiBase::PARAM_ISMULTI => true,
348 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
349 ],
350 'offset' => [
351 ApiBase::PARAM_DFLT => 0,
352 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
353 ],
354 'limit' => [
355 ApiBase::PARAM_DFLT => 10,
356 ApiBase::PARAM_TYPE => 'limit',
357 ApiBase::PARAM_MIN => 1,
358 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
359 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
360 ],
361 'interwiki' => false,
362 'enablerewrites' => false,
363 ];
364
365 $searchConfig = MediaWikiServices::getInstance()->getSearchEngineConfig();
366 $alternatives = $searchConfig->getSearchTypes();
367 if ( count( $alternatives ) > 1 ) {
368 if ( $alternatives[0] === null ) {
369 $alternatives[0] = self::BACKEND_NULL_PARAM;
370 }
371 $params['backend'] = [
372 ApiBase::PARAM_DFLT => $searchConfig->getSearchType(),
373 ApiBase::PARAM_TYPE => $alternatives,
374 ];
375 }
376
377 return $params;
378 }
379
380 protected function getExamplesMessages() {
381 return [
382 'action=query&list=search&srsearch=meaning'
383 => 'apihelp-query+search-example-simple',
384 'action=query&list=search&srwhat=text&srsearch=meaning'
385 => 'apihelp-query+search-example-text',
386 'action=query&generator=search&gsrsearch=meaning&prop=info'
387 => 'apihelp-query+search-example-generator',
388 ];
389 }
390
391 public function getHelpUrls() {
392 return 'https://www.mediawiki.org/wiki/API:Search';
393 }
394 }