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