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