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