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