Merge "Changed tableName so it returns uppercased table names (+prefix) Changed table...
[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( $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 $resultPageSet ApiPageSet
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 $searchInfo = array_flip( $params['info'] );
67 $prop = array_flip( $params['prop'] );
68
69 // Create search engine instance and set options
70 $search = isset( $params['backend'] ) && $params['backend'] != self::BACKEND_NULL_PARAM ?
71 SearchEngine::create( $params['backend'] ) : SearchEngine::create();
72 $search->setLimitOffset( $limit + 1, $params['offset'] );
73 $search->setNamespaces( $params['namespace'] );
74 $search->showRedirects = $params['redirects'];
75
76 $query = $search->transformSearchTerm( $query );
77 $query = $search->replacePrefixes( $query );
78
79 // Perform the actual search
80 if ( $what == 'text' ) {
81 $matches = $search->searchText( $query );
82 } elseif ( $what == 'title' ) {
83 $matches = $search->searchTitle( $query );
84 } elseif ( $what == 'nearmatch' ) {
85 $matches = SearchEngine::getNearMatchResultSet( $query );
86 } else {
87 // We default to title searches; this is a terrible legacy
88 // of the way we initially set up the MySQL fulltext-based
89 // search engine with separate title and text fields.
90 // In the future, the default should be for a combined index.
91 $what = 'title';
92 $matches = $search->searchTitle( $query );
93
94 // Not all search engines support a separate title search,
95 // for instance the Lucene-based engine we use on Wikipedia.
96 // In this case, fall back to full-text search (which will
97 // include titles in it!)
98 if ( is_null( $matches ) ) {
99 $what = 'text';
100 $matches = $search->searchText( $query );
101 }
102 }
103 if ( is_null( $matches ) ) {
104 $this->dieUsage( "{$what} search is disabled", "search-{$what}-disabled" );
105 } elseif ( $matches instanceof Status && !$matches->isGood() ) {
106 $this->dieUsage( $matches->getWikiText(), 'search-error' );
107 }
108
109 $apiResult = $this->getResult();
110 // Add search meta data to result
111 if ( isset( $searchInfo['totalhits'] ) ) {
112 $totalhits = $matches->getTotalHits();
113 if ( $totalhits !== null ) {
114 $apiResult->addValue( array( 'query', 'searchinfo' ),
115 'totalhits', $totalhits );
116 }
117 }
118 if ( isset( $searchInfo['suggestion'] ) && $matches->hasSuggestion() ) {
119 $apiResult->addValue( array( 'query', 'searchinfo' ),
120 'suggestion', $matches->getSuggestionQuery() );
121 }
122
123 // Add the search results to the result
124 $terms = $wgContLang->convertForSearchResult( $matches->termMatches() );
125 $titles = array();
126 $count = 0;
127 $result = $matches->next();
128
129 while ( $result ) {
130 if ( ++ $count > $limit ) {
131 // We've reached the one extra which shows that there are additional items to be had. Stop here...
132 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
133 break;
134 }
135
136 // Silently skip broken and missing titles
137 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
138 $result = $matches->next();
139 continue;
140 }
141
142 $title = $result->getTitle();
143 if ( is_null( $resultPageSet ) ) {
144 $vals = array();
145 ApiQueryBase::addTitleInfo( $vals, $title );
146
147 if ( isset( $prop['snippet'] ) ) {
148 $vals['snippet'] = $result->getTextSnippet( $terms );
149 }
150 if ( isset( $prop['size'] ) ) {
151 $vals['size'] = $result->getByteSize();
152 }
153 if ( isset( $prop['wordcount'] ) ) {
154 $vals['wordcount'] = $result->getWordCount();
155 }
156 if ( isset( $prop['timestamp'] ) ) {
157 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
158 }
159 if ( !is_null( $result->getScore() ) && isset( $prop['score'] ) ) {
160 $vals['score'] = $result->getScore();
161 }
162 if ( isset( $prop['titlesnippet'] ) ) {
163 $vals['titlesnippet'] = $result->getTitleSnippet( $terms );
164 }
165 if ( !is_null( $result->getRedirectTitle() ) ) {
166 if ( isset( $prop['redirecttitle'] ) ) {
167 $vals['redirecttitle'] = $result->getRedirectTitle();
168 }
169 if ( isset( $prop['redirectsnippet'] ) ) {
170 $vals['redirectsnippet'] = $result->getRedirectSnippet( $terms );
171 }
172 }
173 if ( !is_null( $result->getSectionTitle() ) ) {
174 if ( isset( $prop['sectiontitle'] ) ) {
175 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
176 }
177 if ( isset( $prop['sectionsnippet'] ) ) {
178 $vals['sectionsnippet'] = $result->getSectionSnippet();
179 }
180 }
181 if ( isset( $prop['hasrelated'] ) && $result->hasRelated() ) {
182 $vals['hasrelated'] = '';
183 }
184
185 // Add item to results and see whether it fits
186 $fit = $apiResult->addValue( array( 'query', $this->getModuleName() ),
187 null, $vals );
188 if ( !$fit ) {
189 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
190 break;
191 }
192 } else {
193 $titles[] = $title;
194 }
195
196 $result = $matches->next();
197 }
198
199 if ( is_null( $resultPageSet ) ) {
200 $apiResult->setIndexedTagName_internal( array(
201 'query', $this->getModuleName()
202 ), 'p' );
203 } else {
204 $resultPageSet->populateFromTitles( $titles );
205 }
206 }
207
208 public function getCacheMode( $params ) {
209 return 'public';
210 }
211
212 public function getAllowedParams() {
213 global $wgSearchType;
214
215 $params = array(
216 'search' => array(
217 ApiBase::PARAM_TYPE => 'string',
218 ApiBase::PARAM_REQUIRED => true
219 ),
220 'namespace' => array(
221 ApiBase::PARAM_DFLT => NS_MAIN,
222 ApiBase::PARAM_TYPE => 'namespace',
223 ApiBase::PARAM_ISMULTI => true,
224 ),
225 'what' => array(
226 ApiBase::PARAM_DFLT => null,
227 ApiBase::PARAM_TYPE => array(
228 'title',
229 'text',
230 'nearmatch',
231 )
232 ),
233 'info' => array(
234 ApiBase::PARAM_DFLT => 'totalhits|suggestion',
235 ApiBase::PARAM_TYPE => array(
236 'totalhits',
237 'suggestion',
238 ),
239 ApiBase::PARAM_ISMULTI => true,
240 ),
241 'prop' => array(
242 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
243 ApiBase::PARAM_TYPE => array(
244 'size',
245 'wordcount',
246 'timestamp',
247 'score',
248 'snippet',
249 'titlesnippet',
250 'redirecttitle',
251 'redirectsnippet',
252 'sectiontitle',
253 'sectionsnippet',
254 'hasrelated',
255 ),
256 ApiBase::PARAM_ISMULTI => true,
257 ),
258 'redirects' => false,
259 'offset' => 0,
260 'limit' => array(
261 ApiBase::PARAM_DFLT => 10,
262 ApiBase::PARAM_TYPE => 'limit',
263 ApiBase::PARAM_MIN => 1,
264 ApiBase::PARAM_MAX => ApiBase::LIMIT_SML1,
265 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_SML2
266 )
267 );
268
269 $alternatives = SearchEngine::getSearchTypes();
270 if ( count( $alternatives ) > 1 ) {
271 if ( $alternatives[0] === null ) {
272 $alternatives[0] = self::BACKEND_NULL_PARAM;
273 }
274 $params['backend'] = array(
275 ApiBase::PARAM_DFLT => $wgSearchType,
276 ApiBase::PARAM_TYPE => $alternatives,
277 );
278 }
279
280 return $params;
281 }
282
283 public function getParamDescription() {
284 $descriptions = array(
285 'search' => 'Search for all page titles (or content) that has this value',
286 'namespace' => 'The namespace(s) to enumerate',
287 'what' => 'Search inside the text or titles',
288 'info' => 'What metadata to return',
289 'prop' => array(
290 'What properties to return',
291 ' size - Adds the size of the page in bytes',
292 ' wordcount - Adds the word count of the page',
293 ' timestamp - Adds the timestamp of when the page was last edited',
294 ' score - Adds the score (if any) from the search engine',
295 ' snippet - Adds a parsed snippet of the page',
296 ' titlesnippet - Adds a parsed snippet of the page title',
297 ' redirectsnippet - Adds a parsed snippet of the redirect title',
298 ' redirecttitle - Adds the title of the matching redirect',
299 ' sectionsnippet - Adds a parsed snippet of the matching section title',
300 ' sectiontitle - Adds the title of the matching section',
301 ' hasrelated - Indicates whether a related search is available',
302 ),
303 'redirects' => 'Include redirect pages in the search',
304 'offset' => 'Use this value to continue paging (return by query)',
305 'limit' => 'How many total pages to return'
306 );
307
308 if ( count( SearchEngine::getSearchTypes() ) > 1 ) {
309 $descriptions['backend'] = 'Which search backend to use, if not the default';
310 }
311
312 return $descriptions;
313 }
314
315 public function getResultProperties() {
316 return array(
317 '' => array(
318 'ns' => 'namespace',
319 'title' => 'string'
320 ),
321 'snippet' => array(
322 'snippet' => 'string'
323 ),
324 'size' => array(
325 'size' => 'integer'
326 ),
327 'wordcount' => array(
328 'wordcount' => 'integer'
329 ),
330 'timestamp' => array(
331 'timestamp' => 'timestamp'
332 ),
333 'score' => array(
334 'score' => array(
335 ApiBase::PROP_TYPE => 'string',
336 ApiBase::PROP_NULLABLE => true
337 )
338 ),
339 'titlesnippet' => array(
340 'titlesnippet' => 'string'
341 ),
342 'redirecttitle' => array(
343 'redirecttitle' => array(
344 ApiBase::PROP_TYPE => 'string',
345 ApiBase::PROP_NULLABLE => true
346 )
347 ),
348 'redirectsnippet' => array(
349 'redirectsnippet' => array(
350 ApiBase::PROP_TYPE => 'string',
351 ApiBase::PROP_NULLABLE => true
352 )
353 ),
354 'sectiontitle' => array(
355 'sectiontitle' => array(
356 ApiBase::PROP_TYPE => 'string',
357 ApiBase::PROP_NULLABLE => true
358 )
359 ),
360 'sectionsnippet' => array(
361 'sectionsnippet' => array(
362 ApiBase::PROP_TYPE => 'string',
363 ApiBase::PROP_NULLABLE => true
364 )
365 ),
366 'hasrelated' => array(
367 'hasrelated' => 'boolean'
368 )
369 );
370 }
371
372 public function getDescription() {
373 return 'Perform a full text search';
374 }
375
376 public function getPossibleErrors() {
377 return array_merge( parent::getPossibleErrors(), array(
378 array( 'code' => 'search-text-disabled', 'info' => 'text search is disabled' ),
379 array( 'code' => 'search-title-disabled', 'info' => 'title search is disabled' ),
380 array( 'code' => 'search-error', 'info' => 'search error has occurred' ),
381 ) );
382 }
383
384 public function getExamples() {
385 return array(
386 'api.php?action=query&list=search&srsearch=meaning',
387 'api.php?action=query&list=search&srwhat=text&srsearch=meaning',
388 'api.php?action=query&generator=search&gsrsearch=meaning&prop=info',
389 );
390 }
391
392 public function getHelpUrls() {
393 return 'https://www.mediawiki.org/wiki/API:Search';
394 }
395 }