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