Merge "Don't check namespace in SpecialWantedtemplates"
[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( array( 'query', 'searchinfo' ),
129 'totalhits', $totalhits );
130 }
131 }
132 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
133 $apiResult->addValue( array( 'query', 'searchinfo' ),
134 'suggestion', $matches->getSuggestionQuery() );
135 $apiResult->addValue( array( 'query', 'searchinfo' ),
136 'suggestionsnippet', $matches->getSuggestionSnippet() );
137 }
138 if ( isset( $searchInfo['rewrittenquery'] ) && $matches->hasRewrittenQuery() ) {
139 $apiResult->addValue( array( 'query', 'searchinfo' ),
140 'rewrittenquery', $matches->getQueryAfterRewrite() );
141 $apiResult->addValue( array( '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 = array();
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 = array();
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( array( '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 = array(
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 array( '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( array( 'query', 'interwikisearchinfo' ),
267 'totalhits', $totalhits );
268 }
269 }
270
271 if ( $resultPageSet === null ) {
272 $apiResult->addIndexedTagName( array(
273 'query', $this->getModuleName()
274 ), 'p' );
275 if ( $hasInterwikiResults ) {
276 $apiResult->addIndexedTagName( array(
277 'query', 'interwiki' . $this->getModuleName()
278 ), 'p' );
279 }
280 } else {
281 $resultPageSet->populateFromTitles( $titles );
282 $offset = $params['offset'] + 1;
283 foreach ( $titles as $index => $title ) {
284 $resultPageSet->setGeneratorData( $title, array( 'index' => $index + $offset ) );
285 }
286 }
287 }
288
289 public function getCacheMode( $params ) {
290 return 'public';
291 }
292
293 public function getAllowedParams() {
294 $params = array(
295 'search' => array(
296 ApiBase::PARAM_TYPE => 'string',
297 ApiBase::PARAM_REQUIRED => true
298 ),
299 'namespace' => array(
300 ApiBase::PARAM_DFLT => NS_MAIN,
301 ApiBase::PARAM_TYPE => 'namespace',
302 ApiBase::PARAM_ISMULTI => true,
303 ),
304 'what' => array(
305 ApiBase::PARAM_DFLT => null,
306 ApiBase::PARAM_TYPE => array(
307 'title',
308 'text',
309 'nearmatch',
310 )
311 ),
312 'info' => array(
313 ApiBase::PARAM_DFLT => 'totalhits|suggestion|rewrittenquery',
314 ApiBase::PARAM_TYPE => array(
315 'totalhits',
316 'suggestion',
317 'rewrittenquery',
318 ),
319 ApiBase::PARAM_ISMULTI => true,
320 ),
321 'prop' => array(
322 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
323 ApiBase::PARAM_TYPE => array(
324 'size',
325 'wordcount',
326 'timestamp',
327 'snippet',
328 'titlesnippet',
329 'redirecttitle',
330 'redirectsnippet',
331 'sectiontitle',
332 'sectionsnippet',
333 'isfilematch',
334 'categorysnippet',
335 'score', // deprecated
336 'hasrelated', // deprecated
337 ),
338 ApiBase::PARAM_ISMULTI => true,
339 ApiBase::PARAM_HELP_MSG_PER_VALUE => array(),
340 ),
341 'offset' => array(
342 ApiBase::PARAM_DFLT => 0,
343 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
344 ),
345 'limit' => array(
346 ApiBase::PARAM_DFLT => 10,
347 ApiBase::PARAM_TYPE => 'limit',
348 ApiBase::PARAM_MIN => 1,
349 ApiBase::PARAM_MAX => ApiBase::LIMIT_SML1,
350 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_SML2
351 ),
352 'interwiki' => false,
353 'enablerewrites' => false,
354 );
355
356 $alternatives = SearchEngine::getSearchTypes();
357 if ( count( $alternatives ) > 1 ) {
358 if ( $alternatives[0] === null ) {
359 $alternatives[0] = self::BACKEND_NULL_PARAM;
360 }
361 $params['backend'] = array(
362 ApiBase::PARAM_DFLT => $this->getConfig()->get( 'SearchType' ),
363 ApiBase::PARAM_TYPE => $alternatives,
364 );
365 }
366
367 return $params;
368 }
369
370 protected function getExamplesMessages() {
371 return array(
372 'action=query&list=search&srsearch=meaning'
373 => 'apihelp-query+search-example-simple',
374 'action=query&list=search&srwhat=text&srsearch=meaning'
375 => 'apihelp-query+search-example-text',
376 'action=query&generator=search&gsrsearch=meaning&prop=info'
377 => 'apihelp-query+search-example-generator',
378 );
379 }
380
381 public function getHelpUrls() {
382 return 'https://www.mediawiki.org/wiki/API:Search';
383 }
384 }