Merge "API: Use message-per-value for apihelp-query+recentchanges-param-prop"
[lhc/web/wiklou.git] / includes / api / ApiQuery.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 7, 2006
6 *
7 * Copyright © 2006 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 * This is the main query class. It behaves similar to ApiMain: based on the
29 * parameters given, it will create a list of titles to work on (an ApiPageSet
30 * object), instantiate and execute various property/list/meta modules, and
31 * assemble all resulting data into a single ApiResult object.
32 *
33 * In generator mode, a generator will be executed first to populate a second
34 * ApiPageSet object, and that object will be used for all subsequent modules.
35 *
36 * @ingroup API
37 */
38 class ApiQuery extends ApiBase {
39
40 /**
41 * List of Api Query prop modules
42 * @var array
43 */
44 private static $QueryPropModules = array(
45 'categories' => 'ApiQueryCategories',
46 'categoryinfo' => 'ApiQueryCategoryInfo',
47 'contributors' => 'ApiQueryContributors',
48 'deletedrevisions' => 'ApiQueryDeletedRevisions',
49 'duplicatefiles' => 'ApiQueryDuplicateFiles',
50 'extlinks' => 'ApiQueryExternalLinks',
51 'fileusage' => 'ApiQueryBacklinksprop',
52 'images' => 'ApiQueryImages',
53 'imageinfo' => 'ApiQueryImageInfo',
54 'info' => 'ApiQueryInfo',
55 'links' => 'ApiQueryLinks',
56 'linkshere' => 'ApiQueryBacklinksprop',
57 'iwlinks' => 'ApiQueryIWLinks',
58 'langlinks' => 'ApiQueryLangLinks',
59 'pageprops' => 'ApiQueryPageProps',
60 'redirects' => 'ApiQueryBacklinksprop',
61 'revisions' => 'ApiQueryRevisions',
62 'stashimageinfo' => 'ApiQueryStashImageInfo',
63 'templates' => 'ApiQueryLinks',
64 'transcludedin' => 'ApiQueryBacklinksprop',
65 );
66
67 /**
68 * List of Api Query list modules
69 * @var array
70 */
71 private static $QueryListModules = array(
72 'allcategories' => 'ApiQueryAllCategories',
73 'alldeletedrevisions' => 'ApiQueryAllDeletedRevisions',
74 'allfileusages' => 'ApiQueryAllLinks',
75 'allimages' => 'ApiQueryAllImages',
76 'alllinks' => 'ApiQueryAllLinks',
77 'allpages' => 'ApiQueryAllPages',
78 'allredirects' => 'ApiQueryAllLinks',
79 'alltransclusions' => 'ApiQueryAllLinks',
80 'allusers' => 'ApiQueryAllUsers',
81 'backlinks' => 'ApiQueryBacklinks',
82 'blocks' => 'ApiQueryBlocks',
83 'categorymembers' => 'ApiQueryCategoryMembers',
84 'deletedrevs' => 'ApiQueryDeletedrevs',
85 'embeddedin' => 'ApiQueryBacklinks',
86 'exturlusage' => 'ApiQueryExtLinksUsage',
87 'filearchive' => 'ApiQueryFilearchive',
88 'imageusage' => 'ApiQueryBacklinks',
89 'iwbacklinks' => 'ApiQueryIWBacklinks',
90 'langbacklinks' => 'ApiQueryLangBacklinks',
91 'logevents' => 'ApiQueryLogEvents',
92 'pageswithprop' => 'ApiQueryPagesWithProp',
93 'pagepropnames' => 'ApiQueryPagePropNames',
94 'prefixsearch' => 'ApiQueryPrefixSearch',
95 'protectedtitles' => 'ApiQueryProtectedTitles',
96 'querypage' => 'ApiQueryQueryPage',
97 'random' => 'ApiQueryRandom',
98 'recentchanges' => 'ApiQueryRecentChanges',
99 'search' => 'ApiQuerySearch',
100 'tags' => 'ApiQueryTags',
101 'usercontribs' => 'ApiQueryContributions',
102 'users' => 'ApiQueryUsers',
103 'watchlist' => 'ApiQueryWatchlist',
104 'watchlistraw' => 'ApiQueryWatchlistRaw',
105 );
106
107 /**
108 * List of Api Query meta modules
109 * @var array
110 */
111 private static $QueryMetaModules = array(
112 'allmessages' => 'ApiQueryAllMessages',
113 'siteinfo' => 'ApiQuerySiteinfo',
114 'userinfo' => 'ApiQueryUserInfo',
115 'filerepoinfo' => 'ApiQueryFileRepoInfo',
116 'tokens' => 'ApiQueryTokens',
117 );
118
119 /**
120 * @var ApiPageSet
121 */
122 private $mPageSet;
123
124 private $mParams;
125 private $mNamedDB = array();
126 private $mModuleMgr;
127
128 /**
129 * @param ApiMain $main
130 * @param string $action
131 */
132 public function __construct( ApiMain $main, $action ) {
133 parent::__construct( $main, $action );
134
135 $this->mModuleMgr = new ApiModuleManager( $this );
136
137 // Allow custom modules to be added in LocalSettings.php
138 $config = $this->getConfig();
139 $this->mModuleMgr->addModules( self::$QueryPropModules, 'prop' );
140 $this->mModuleMgr->addModules( $config->get( 'APIPropModules' ), 'prop' );
141 $this->mModuleMgr->addModules( self::$QueryListModules, 'list' );
142 $this->mModuleMgr->addModules( $config->get( 'APIListModules' ), 'list' );
143 $this->mModuleMgr->addModules( self::$QueryMetaModules, 'meta' );
144 $this->mModuleMgr->addModules( $config->get( 'APIMetaModules' ), 'meta' );
145
146 Hooks::run( 'ApiQuery::moduleManager', array( $this->mModuleMgr ) );
147
148 // Create PageSet that will process titles/pageids/revids/generator
149 $this->mPageSet = new ApiPageSet( $this );
150 }
151
152 /**
153 * Overrides to return this instance's module manager.
154 * @return ApiModuleManager
155 */
156 public function getModuleManager() {
157 return $this->mModuleMgr;
158 }
159
160 /**
161 * Get the query database connection with the given name.
162 * If no such connection has been requested before, it will be created.
163 * Subsequent calls with the same $name will return the same connection
164 * as the first, regardless of the values of $db and $groups
165 * @param string $name Name to assign to the database connection
166 * @param int $db One of the DB_* constants
167 * @param array $groups Query groups
168 * @return DatabaseBase
169 */
170 public function getNamedDB( $name, $db, $groups ) {
171 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
172 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
173 }
174
175 return $this->mNamedDB[$name];
176 }
177
178 /**
179 * Gets the set of pages the user has requested (or generated)
180 * @return ApiPageSet
181 */
182 public function getPageSet() {
183 return $this->mPageSet;
184 }
185
186 /**
187 * Get the array mapping module names to class names
188 * @deprecated since 1.21, use getModuleManager()'s methods instead
189 * @return array Array(modulename => classname)
190 */
191 public function getModules() {
192 wfDeprecated( __METHOD__, '1.21' );
193
194 return $this->getModuleManager()->getNamesWithClasses();
195 }
196
197 /**
198 * Get the generators array mapping module names to class names
199 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
200 * @return array Array(modulename => classname)
201 */
202 public function getGenerators() {
203 wfDeprecated( __METHOD__, '1.21' );
204 $gens = array();
205 foreach ( $this->mModuleMgr->getNamesWithClasses() as $name => $class ) {
206 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
207 $gens[$name] = $class;
208 }
209 }
210
211 return $gens;
212 }
213
214 /**
215 * Get whether the specified module is a prop, list or a meta query module
216 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
217 * @param string $moduleName Name of the module to find type for
218 * @return string|null
219 */
220 function getModuleType( $moduleName ) {
221 return $this->getModuleManager()->getModuleGroup( $moduleName );
222 }
223
224 /**
225 * @return ApiFormatRaw|null
226 */
227 public function getCustomPrinter() {
228 // If &exportnowrap is set, use the raw formatter
229 if ( $this->getParameter( 'export' ) &&
230 $this->getParameter( 'exportnowrap' )
231 ) {
232 return new ApiFormatRaw( $this->getMain(),
233 $this->getMain()->createPrinterByName( 'xml' ) );
234 } else {
235 return null;
236 }
237 }
238
239 /**
240 * Query execution happens in the following steps:
241 * #1 Create a PageSet object with any pages requested by the user
242 * #2 If using a generator, execute it to get a new ApiPageSet object
243 * #3 Instantiate all requested modules.
244 * This way the PageSet object will know what shared data is required,
245 * and minimize DB calls.
246 * #4 Output all normalization and redirect resolution information
247 * #5 Execute all requested modules
248 */
249 public function execute() {
250 $this->mParams = $this->extractRequestParams();
251
252 // Instantiate requested modules
253 $allModules = array();
254 $this->instantiateModules( $allModules, 'prop' );
255 $propModules = array_keys( $allModules );
256 $this->instantiateModules( $allModules, 'list' );
257 $this->instantiateModules( $allModules, 'meta' );
258
259 // Filter modules based on continue parameter
260 $continuationManager = new ApiContinuationManager( $this, $allModules, $propModules );
261 $this->setContinuationManager( $continuationManager );
262 $modules = $continuationManager->getRunModules();
263
264 if ( !$continuationManager->isGeneratorDone() ) {
265 // Query modules may optimize data requests through the $this->getPageSet()
266 // object by adding extra fields from the page table.
267 foreach ( $modules as $module ) {
268 $module->requestExtraData( $this->mPageSet );
269 }
270 // Populate page/revision information
271 $this->mPageSet->execute();
272 // Record page information (title, namespace, if exists, etc)
273 $this->outputGeneralPageInfo();
274 } else {
275 $this->mPageSet->executeDryRun();
276 }
277
278 $cacheMode = $this->mPageSet->getCacheMode();
279 $stats = $this->getContext()->getStats();
280
281 // Execute all unfinished modules
282 /** @var $module ApiQueryBase */
283 foreach ( $modules as $module ) {
284 $params = $module->extractRequestParams();
285 $cacheMode = $this->mergeCacheMode(
286 $cacheMode, $module->getCacheMode( $params ) );
287
288 $statsPath = 'api.modules.' . strtr( $module->getModulePath(), '+', '.' );
289 $metric = $stats->increment( $statsPath );
290 $metric->setSampleRate( 0.001 );
291
292 $module->execute();
293 Hooks::run( 'APIQueryAfterExecute', array( &$module ) );
294 }
295
296 // Set the cache mode
297 $this->getMain()->setCacheMode( $cacheMode );
298
299 // Write the continuation data into the result
300 $this->setContinuationManager( null );
301 if ( $this->mParams['rawcontinue'] ) {
302 $data = $continuationManager->getRawContinuation();
303 if ( $data ) {
304 $this->getResult()->addValue( null, 'query-continue', $data,
305 ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
306 }
307 } else {
308 $continuationManager->setContinuationIntoResult( $this->getResult() );
309 }
310
311 /// @todo: Remove this after a suitable period of time. When REL1_26 is cut, if not before.
312 if ( $this->mParams['continue'] === null && !$this->mParams['rawcontinue'] &&
313 $this->getResult()->getResultData( 'continue' ) !== null
314 ) {
315 $this->setWarning(
316 'Formatting of continuation data has changed. ' .
317 'To receive raw query-continue data, use the \'rawcontinue\' parameter. ' .
318 'To silence this warning, pass an empty string for \'continue\' in the initial query.'
319 );
320 }
321 }
322
323 /**
324 * Update a cache mode string, applying the cache mode of a new module to it.
325 * The cache mode may increase in the level of privacy, but public modules
326 * added to private data do not decrease the level of privacy.
327 *
328 * @param string $cacheMode
329 * @param string $modCacheMode
330 * @return string
331 */
332 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
333 if ( $modCacheMode === 'anon-public-user-private' ) {
334 if ( $cacheMode !== 'private' ) {
335 $cacheMode = 'anon-public-user-private';
336 }
337 } elseif ( $modCacheMode === 'public' ) {
338 // do nothing, if it's public already it will stay public
339 } else { // private
340 $cacheMode = 'private';
341 }
342
343 return $cacheMode;
344 }
345
346 /**
347 * Create instances of all modules requested by the client
348 * @param array $modules To append instantiated modules to
349 * @param string $param Parameter name to read modules from
350 */
351 private function instantiateModules( &$modules, $param ) {
352 $wasPosted = $this->getRequest()->wasPosted();
353 if ( isset( $this->mParams[$param] ) ) {
354 foreach ( $this->mParams[$param] as $moduleName ) {
355 $instance = $this->mModuleMgr->getModule( $moduleName, $param );
356 if ( $instance === null ) {
357 ApiBase::dieDebug( __METHOD__, 'Error instantiating module' );
358 }
359 if ( !$wasPosted && $instance->mustBePosted() ) {
360 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $moduleName ) );
361 }
362 // Ignore duplicates. TODO 2.0: die()?
363 if ( !array_key_exists( $moduleName, $modules ) ) {
364 $modules[$moduleName] = $instance;
365 }
366 }
367 }
368 }
369
370 /**
371 * Appends an element for each page in the current pageSet with the
372 * most general information (id, title), plus any title normalizations
373 * and missing or invalid title/pageids/revids.
374 */
375 private function outputGeneralPageInfo() {
376 $pageSet = $this->getPageSet();
377 $result = $this->getResult();
378
379 // We can't really handle max-result-size failure here, but we need to
380 // check anyway in case someone set the limit stupidly low.
381 $fit = true;
382
383 $values = $pageSet->getNormalizedTitlesAsResult( $result );
384 if ( $values ) {
385 $fit = $fit && $result->addValue( 'query', 'normalized', $values );
386 }
387 $values = $pageSet->getConvertedTitlesAsResult( $result );
388 if ( $values ) {
389 $fit = $fit && $result->addValue( 'query', 'converted', $values );
390 }
391 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->mParams['iwurl'] );
392 if ( $values ) {
393 $fit = $fit && $result->addValue( 'query', 'interwiki', $values );
394 }
395 $values = $pageSet->getRedirectTitlesAsResult( $result );
396 if ( $values ) {
397 $fit = $fit && $result->addValue( 'query', 'redirects', $values );
398 }
399 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
400 if ( $values ) {
401 $fit = $fit && $result->addValue( 'query', 'badrevids', $values );
402 }
403
404 // Page elements
405 $pages = array();
406
407 // Report any missing titles
408 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
409 $vals = array();
410 ApiQueryBase::addTitleInfo( $vals, $title );
411 $vals['missing'] = true;
412 $pages[$fakeId] = $vals;
413 }
414 // Report any invalid titles
415 foreach ( $pageSet->getInvalidTitlesAndReasons() as $fakeId => $data ) {
416 $pages[$fakeId] = $data + array( 'invalid' => true );
417 }
418 // Report any missing page ids
419 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
420 $pages[$pageid] = array(
421 'pageid' => $pageid,
422 'missing' => true
423 );
424 }
425 // Report special pages
426 /** @var $title Title */
427 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
428 $vals = array();
429 ApiQueryBase::addTitleInfo( $vals, $title );
430 $vals['special'] = true;
431 if ( $title->isSpecialPage() &&
432 !SpecialPageFactory::exists( $title->getDBkey() )
433 ) {
434 $vals['missing'] = true;
435 } elseif ( $title->getNamespace() == NS_MEDIA &&
436 !wfFindFile( $title )
437 ) {
438 $vals['missing'] = true;
439 }
440 $pages[$fakeId] = $vals;
441 }
442
443 // Output general page information for found titles
444 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
445 $vals = array();
446 $vals['pageid'] = $pageid;
447 ApiQueryBase::addTitleInfo( $vals, $title );
448 $pages[$pageid] = $vals;
449 }
450
451 if ( count( $pages ) ) {
452 $pageSet->populateGeneratorData( $pages );
453 ApiResult::setArrayType( $pages, 'BCarray' );
454
455 if ( $this->mParams['indexpageids'] ) {
456 $pageIDs = array_keys( ApiResult::stripMetadataNonRecursive( $pages ) );
457 // json treats all map keys as strings - converting to match
458 $pageIDs = array_map( 'strval', $pageIDs );
459 ApiResult::setIndexedTagName( $pageIDs, 'id' );
460 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
461 }
462
463 ApiResult::setIndexedTagName( $pages, 'page' );
464 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
465 }
466
467 if ( !$fit ) {
468 $this->dieUsage(
469 'The value of $wgAPIMaxResultSize on this wiki is ' .
470 'too small to hold basic result information',
471 'badconfig'
472 );
473 }
474
475 if ( $this->mParams['export'] ) {
476 $this->doExport( $pageSet, $result );
477 }
478 }
479
480 /**
481 * This method is called by the generator base when generator in the smart-continue
482 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
483 * until the post-processing when it is known if the generation should continue or repeat.
484 * @deprecated since 1.24
485 * @param ApiQueryGeneratorBase $module Generator module
486 * @param string $paramName
487 * @param mixed $paramValue
488 * @return bool True if processed, false if this is a legacy continue
489 */
490 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
491 wfDeprecated( __METHOD__, '1.24' );
492 $this->getContinuationManager()->addGeneratorContinueParam( $module, $paramName, $paramValue );
493 return !$this->getParameter( 'rawcontinue' );
494 }
495
496 /**
497 * @param ApiPageSet $pageSet Pages to be exported
498 * @param ApiResult $result Result to output to
499 */
500 private function doExport( $pageSet, $result ) {
501 $exportTitles = array();
502 $titles = $pageSet->getGoodTitles();
503 if ( count( $titles ) ) {
504 $user = $this->getUser();
505 /** @var $title Title */
506 foreach ( $titles as $title ) {
507 if ( $title->userCan( 'read', $user ) ) {
508 $exportTitles[] = $title;
509 }
510 }
511 }
512
513 $exporter = new WikiExporter( $this->getDB() );
514 // WikiExporter writes to stdout, so catch its
515 // output with an ob
516 ob_start();
517 $exporter->openStream();
518 foreach ( $exportTitles as $title ) {
519 $exporter->pageByTitle( $title );
520 }
521 $exporter->closeStream();
522 $exportxml = ob_get_contents();
523 ob_end_clean();
524
525 // Don't check the size of exported stuff
526 // It's not continuable, so it would cause more
527 // problems than it'd solve
528 if ( $this->mParams['exportnowrap'] ) {
529 $result->reset();
530 // Raw formatter will handle this
531 $result->addValue( null, 'text', $exportxml, ApiResult::NO_SIZE_CHECK );
532 $result->addValue( null, 'mime', 'text/xml', ApiResult::NO_SIZE_CHECK );
533 } else {
534 $result->addValue( 'query', 'export', $exportxml, ApiResult::NO_SIZE_CHECK );
535 $result->addValue( 'query', ApiResult::META_BC_SUBELEMENTS, array( 'export' ) );
536 }
537 }
538
539 public function getAllowedParams( $flags = 0 ) {
540 $result = array(
541 'prop' => array(
542 ApiBase::PARAM_ISMULTI => true,
543 ApiBase::PARAM_TYPE => 'submodule',
544 ),
545 'list' => array(
546 ApiBase::PARAM_ISMULTI => true,
547 ApiBase::PARAM_TYPE => 'submodule',
548 ),
549 'meta' => array(
550 ApiBase::PARAM_ISMULTI => true,
551 ApiBase::PARAM_TYPE => 'submodule',
552 ),
553 'indexpageids' => false,
554 'export' => false,
555 'exportnowrap' => false,
556 'iwurl' => false,
557 'continue' => array(
558 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
559 ),
560 'rawcontinue' => false,
561 );
562 if ( $flags ) {
563 $result += $this->getPageSet()->getFinalParams( $flags );
564 }
565
566 return $result;
567 }
568
569 /**
570 * Override the parent to generate help messages for all available query modules.
571 * @deprecated since 1.25
572 * @return string
573 */
574 public function makeHelpMsg() {
575 wfDeprecated( __METHOD__, '1.25' );
576
577 // Use parent to make default message for the query module
578 $msg = parent::makeHelpMsg();
579
580 $querySeparator = str_repeat( '--- ', 12 );
581 $moduleSeparator = str_repeat( '*** ', 14 );
582 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
583 $msg .= $this->makeHelpMsgHelper( 'prop' );
584 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
585 $msg .= $this->makeHelpMsgHelper( 'list' );
586 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
587 $msg .= $this->makeHelpMsgHelper( 'meta' );
588 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
589
590 return $msg;
591 }
592
593 /**
594 * For all modules of a given group, generate help messages and join them together
595 * @deprecated since 1.25
596 * @param string $group Module group
597 * @return string
598 */
599 private function makeHelpMsgHelper( $group ) {
600 $moduleDescriptions = array();
601
602 $moduleNames = $this->mModuleMgr->getNames( $group );
603 sort( $moduleNames );
604 foreach ( $moduleNames as $name ) {
605 /**
606 * @var $module ApiQueryBase
607 */
608 $module = $this->mModuleMgr->getModule( $name );
609
610 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
611 $msg2 = $module->makeHelpMsg();
612 if ( $msg2 !== false ) {
613 $msg .= $msg2;
614 }
615 if ( $module instanceof ApiQueryGeneratorBase ) {
616 $msg .= "Generator:\n This module may be used as a generator\n";
617 }
618 $moduleDescriptions[] = $msg;
619 }
620
621 return implode( "\n", $moduleDescriptions );
622 }
623
624 public function shouldCheckMaxlag() {
625 return true;
626 }
627
628 protected function getExamplesMessages() {
629 return array(
630 'action=query&prop=revisions&meta=siteinfo&' .
631 'titles=Main%20Page&rvprop=user|comment&continue='
632 => 'apihelp-query-example-revisions',
633 'action=query&generator=allpages&gapprefix=API/&prop=revisions&continue='
634 => 'apihelp-query-example-allpages',
635 );
636 }
637
638 public function getHelpUrls() {
639 return array(
640 'https://www.mediawiki.org/wiki/API:Query',
641 'https://www.mediawiki.org/wiki/API:Meta',
642 'https://www.mediawiki.org/wiki/API:Properties',
643 'https://www.mediawiki.org/wiki/API:Lists',
644 );
645 }
646 }