Merge "format the tests/phpunit/TODO document for readability"
[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 // Create search engine instance and set options
71 $search = isset( $params['backend'] ) && $params['backend'] != self::BACKEND_NULL_PARAM ?
72 SearchEngine::create( $params['backend'] ) : SearchEngine::create();
73 $search->setLimitOffset( $limit + 1, $params['offset'] );
74 $search->setNamespaces( $params['namespace'] );
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
132 // additional items to be had. Stop here...
133 $this->setContinueEnumParameter( 'offset', $params['offset'] + $params['limit'] );
134 break;
135 }
136
137 // Silently skip broken and missing titles
138 if ( $result->isBrokenTitle() || $result->isMissingRevision() ) {
139 $result = $matches->next();
140 continue;
141 }
142
143 $title = $result->getTitle();
144 if ( is_null( $resultPageSet ) ) {
145 $vals = array();
146 ApiQueryBase::addTitleInfo( $vals, $title );
147
148 if ( isset( $prop['snippet'] ) ) {
149 $vals['snippet'] = $result->getTextSnippet( $terms );
150 }
151 if ( isset( $prop['size'] ) ) {
152 $vals['size'] = $result->getByteSize();
153 }
154 if ( isset( $prop['wordcount'] ) ) {
155 $vals['wordcount'] = $result->getWordCount();
156 }
157 if ( isset( $prop['timestamp'] ) ) {
158 $vals['timestamp'] = wfTimestamp( TS_ISO_8601, $result->getTimestamp() );
159 }
160 if ( !is_null( $result->getScore() ) && isset( $prop['score'] ) ) {
161 $vals['score'] = $result->getScore();
162 }
163 if ( isset( $prop['titlesnippet'] ) ) {
164 $vals['titlesnippet'] = $result->getTitleSnippet( $terms );
165 }
166 if ( !is_null( $result->getRedirectTitle() ) ) {
167 if ( isset( $prop['redirecttitle'] ) ) {
168 $vals['redirecttitle'] = $result->getRedirectTitle();
169 }
170 if ( isset( $prop['redirectsnippet'] ) ) {
171 $vals['redirectsnippet'] = $result->getRedirectSnippet( $terms );
172 }
173 }
174 if ( !is_null( $result->getSectionTitle() ) ) {
175 if ( isset( $prop['sectiontitle'] ) ) {
176 $vals['sectiontitle'] = $result->getSectionTitle()->getFragment();
177 }
178 if ( isset( $prop['sectionsnippet'] ) ) {
179 $vals['sectionsnippet'] = $result->getSectionSnippet();
180 }
181 }
182 if ( isset( $prop['hasrelated'] ) && $result->hasRelated() ) {
183 $vals['hasrelated'] = '';
184 }
185
186 // Add item to results and see whether it fits
187 $fit = $apiResult->addValue( array( 'query', $this->getModuleName() ),
188 null, $vals );
189 if ( !$fit ) {
190 $this->setContinueEnumParameter( 'offset', $params['offset'] + $count - 1 );
191 break;
192 }
193 } else {
194 $titles[] = $title;
195 }
196
197 $result = $matches->next();
198 }
199
200 $hasInterwikiResults = false;
201 if ( $interwiki && $resultPageSet === null && $matches->hasInterwikiResults() ) {
202 $matches = $matches->getInterwikiResults();
203 $iwprefixes = array();
204 $hasInterwikiResults = true;
205
206 // Include number of results if requested
207 if ( isset( $searchInfo['totalhits'] ) ) {
208 $totalhits = $matches->getTotalHits();
209 if ( $totalhits !== null ) {
210 $apiResult->addValue( array( 'query', 'interwikisearchinfo' ),
211 'totalhits', $totalhits );
212 }
213 }
214
215 $result = $matches->next();
216 while ( $result ) {
217 $title = $result->getTitle();
218 $vals = array(
219 'namespace' => $result->getInterwikiNamespaceText(),
220 'title' => $title->getText(),
221 'url' => $title->getFullUrl(),
222 );
223
224 // Add item to results and see whether it fits
225 $fit = $apiResult->addValue(
226 array( 'query', 'interwiki' . $this->getModuleName(), $result->getInterwikiPrefix() ),
227 null,
228 $vals
229 );
230
231 if ( !$fit ) {
232 // We hit the limit. We can't really provide any meaningful
233 // pagination info so just bail out
234 break;
235 }
236
237 $result = $matches->next();
238 }
239 }
240
241 if ( is_null( $resultPageSet ) ) {
242 $apiResult->setIndexedTagName_internal( array(
243 'query', $this->getModuleName()
244 ), 'p' );
245 if ( $hasInterwikiResults ) {
246 $apiResult->setIndexedTagName_internal( array(
247 'query', 'interwiki' . $this->getModuleName()
248 ), 'p' );
249 }
250 } else {
251 $resultPageSet->populateFromTitles( $titles );
252 }
253 }
254
255 public function getCacheMode( $params ) {
256 return 'public';
257 }
258
259 public function getAllowedParams() {
260 global $wgSearchType;
261
262 $params = array(
263 'search' => array(
264 ApiBase::PARAM_TYPE => 'string',
265 ApiBase::PARAM_REQUIRED => true
266 ),
267 'namespace' => array(
268 ApiBase::PARAM_DFLT => NS_MAIN,
269 ApiBase::PARAM_TYPE => 'namespace',
270 ApiBase::PARAM_ISMULTI => true,
271 ),
272 'what' => array(
273 ApiBase::PARAM_DFLT => null,
274 ApiBase::PARAM_TYPE => array(
275 'title',
276 'text',
277 'nearmatch',
278 )
279 ),
280 'info' => array(
281 ApiBase::PARAM_DFLT => 'totalhits|suggestion',
282 ApiBase::PARAM_TYPE => array(
283 'totalhits',
284 'suggestion',
285 ),
286 ApiBase::PARAM_ISMULTI => true,
287 ),
288 'prop' => array(
289 ApiBase::PARAM_DFLT => 'size|wordcount|timestamp|snippet',
290 ApiBase::PARAM_TYPE => array(
291 'size',
292 'wordcount',
293 'timestamp',
294 'score',
295 'snippet',
296 'titlesnippet',
297 'redirecttitle',
298 'redirectsnippet',
299 'sectiontitle',
300 'sectionsnippet',
301 'hasrelated',
302 ),
303 ApiBase::PARAM_ISMULTI => true,
304 ),
305 'offset' => 0,
306 'limit' => array(
307 ApiBase::PARAM_DFLT => 10,
308 ApiBase::PARAM_TYPE => 'limit',
309 ApiBase::PARAM_MIN => 1,
310 ApiBase::PARAM_MAX => ApiBase::LIMIT_SML1,
311 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_SML2
312 ),
313 'interwiki' => false,
314 );
315
316 $alternatives = SearchEngine::getSearchTypes();
317 if ( count( $alternatives ) > 1 ) {
318 if ( $alternatives[0] === null ) {
319 $alternatives[0] = self::BACKEND_NULL_PARAM;
320 }
321 $params['backend'] = array(
322 ApiBase::PARAM_DFLT => $wgSearchType,
323 ApiBase::PARAM_TYPE => $alternatives,
324 );
325 }
326
327 return $params;
328 }
329
330 public function getParamDescription() {
331 $descriptions = array(
332 'search' => 'Search for all page titles (or content) that has this value',
333 'namespace' => 'The namespace(s) to enumerate',
334 'what' => 'Search inside the text or titles',
335 'info' => 'What metadata to return',
336 'prop' => array(
337 'What properties to return',
338 ' size - Adds the size of the page in bytes',
339 ' wordcount - Adds the word count of the page',
340 ' timestamp - Adds the timestamp of when the page was last edited',
341 ' score - Adds the score (if any) from the search engine',
342 ' snippet - Adds a parsed snippet of the page',
343 ' titlesnippet - Adds a parsed snippet of the page title',
344 ' redirectsnippet - Adds a parsed snippet of the redirect title',
345 ' redirecttitle - Adds the title of the matching redirect',
346 ' sectionsnippet - Adds a parsed snippet of the matching section title',
347 ' sectiontitle - Adds the title of the matching section',
348 ' hasrelated - Indicates whether a related search is available',
349 ),
350 'offset' => 'Use this value to continue paging (return by query)',
351 'limit' => 'How many total pages to return',
352 'interwiki' => 'Include interwiki results in the search, if available'
353 );
354
355 if ( count( SearchEngine::getSearchTypes() ) > 1 ) {
356 $descriptions['backend'] = 'Which search backend to use, if not the default';
357 }
358
359 return $descriptions;
360 }
361
362 public function getResultProperties() {
363 return array(
364 '' => array(
365 'ns' => 'namespace',
366 'title' => 'string'
367 ),
368 'snippet' => array(
369 'snippet' => 'string'
370 ),
371 'size' => array(
372 'size' => 'integer'
373 ),
374 'wordcount' => array(
375 'wordcount' => 'integer'
376 ),
377 'timestamp' => array(
378 'timestamp' => 'timestamp'
379 ),
380 'score' => array(
381 'score' => array(
382 ApiBase::PROP_TYPE => 'string',
383 ApiBase::PROP_NULLABLE => true
384 )
385 ),
386 'titlesnippet' => array(
387 'titlesnippet' => 'string'
388 ),
389 'redirecttitle' => array(
390 'redirecttitle' => array(
391 ApiBase::PROP_TYPE => 'string',
392 ApiBase::PROP_NULLABLE => true
393 )
394 ),
395 'redirectsnippet' => array(
396 'redirectsnippet' => array(
397 ApiBase::PROP_TYPE => 'string',
398 ApiBase::PROP_NULLABLE => true
399 )
400 ),
401 'sectiontitle' => array(
402 'sectiontitle' => array(
403 ApiBase::PROP_TYPE => 'string',
404 ApiBase::PROP_NULLABLE => true
405 )
406 ),
407 'sectionsnippet' => array(
408 'sectionsnippet' => array(
409 ApiBase::PROP_TYPE => 'string',
410 ApiBase::PROP_NULLABLE => true
411 )
412 ),
413 'hasrelated' => array(
414 'hasrelated' => 'boolean'
415 )
416 );
417 }
418
419 public function getDescription() {
420 return 'Perform a full text search.';
421 }
422
423 public function getPossibleErrors() {
424 return array_merge( parent::getPossibleErrors(), array(
425 array( 'code' => 'search-text-disabled', 'info' => 'text search is disabled' ),
426 array( 'code' => 'search-title-disabled', 'info' => 'title search is disabled' ),
427 array( 'code' => 'search-error', 'info' => 'search error has occurred' ),
428 ) );
429 }
430
431 public function getExamples() {
432 return array(
433 'api.php?action=query&list=search&srsearch=meaning',
434 'api.php?action=query&list=search&srwhat=text&srsearch=meaning',
435 'api.php?action=query&generator=search&gsrsearch=meaning&prop=info',
436 );
437 }
438
439 public function getHelpUrls() {
440 return 'https://www.mediawiki.org/wiki/API:Search';
441 }
442 }