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