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