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