5 * Created on Sep 7, 2006
7 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
33 * This is the main query class. It behaves similar to ApiMain: based on the
34 * parameters given, it will create a list of titles to work on (an ApiPageSet
35 * object), instantiate and execute various property/list/meta modules, and
36 * assemble all resulting data into a single ApiResult object.
38 * In generator mode, a generator will be executed first to populate a second
39 * ApiPageSet object, and that object will be used for all subsequent modules.
43 class ApiQuery
extends ApiBase
{
45 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
47 private $params, $redirects, $convertTitles;
49 private $mQueryPropModules = array(
50 'info' => 'ApiQueryInfo',
51 'revisions' => 'ApiQueryRevisions',
52 'links' => 'ApiQueryLinks',
53 'iwlinks' => 'ApiQueryIWLinks',
54 'langlinks' => 'ApiQueryLangLinks',
55 'images' => 'ApiQueryImages',
56 'imageinfo' => 'ApiQueryImageInfo',
57 'stashimageinfo' => 'ApiQueryStashImageInfo',
58 'templates' => 'ApiQueryLinks',
59 'categories' => 'ApiQueryCategories',
60 'extlinks' => 'ApiQueryExternalLinks',
61 'categoryinfo' => 'ApiQueryCategoryInfo',
62 'duplicatefiles' => 'ApiQueryDuplicateFiles',
63 'pageprops' => 'ApiQueryPageProps',
66 private $mQueryListModules = array(
67 'allimages' => 'ApiQueryAllimages',
68 'allpages' => 'ApiQueryAllpages',
69 'alllinks' => 'ApiQueryAllLinks',
70 'allcategories' => 'ApiQueryAllCategories',
71 'allusers' => 'ApiQueryAllUsers',
72 'backlinks' => 'ApiQueryBacklinks',
73 'blocks' => 'ApiQueryBlocks',
74 'categorymembers' => 'ApiQueryCategoryMembers',
75 'deletedrevs' => 'ApiQueryDeletedrevs',
76 'embeddedin' => 'ApiQueryBacklinks',
77 'filearchive' => 'ApiQueryFilearchive',
78 'imageusage' => 'ApiQueryBacklinks',
79 'iwbacklinks' => 'ApiQueryIWBacklinks',
80 'logevents' => 'ApiQueryLogEvents',
81 'recentchanges' => 'ApiQueryRecentChanges',
82 'search' => 'ApiQuerySearch',
83 'tags' => 'ApiQueryTags',
84 'usercontribs' => 'ApiQueryContributions',
85 'watchlist' => 'ApiQueryWatchlist',
86 'watchlistraw' => 'ApiQueryWatchlistRaw',
87 'exturlusage' => 'ApiQueryExtLinksUsage',
88 'users' => 'ApiQueryUsers',
89 'random' => 'ApiQueryRandom',
90 'protectedtitles' => 'ApiQueryProtectedTitles',
91 'querypage' => 'ApiQueryQueryPage',
94 private $mQueryMetaModules = array(
95 'siteinfo' => 'ApiQuerySiteinfo',
96 'userinfo' => 'ApiQueryUserInfo',
97 'allmessages' => 'ApiQueryAllmessages',
100 private $mSlaveDB = null;
101 private $mNamedDB = array();
103 public function __construct( $main, $action ) {
104 parent
::__construct( $main, $action );
106 // Allow custom modules to be added in LocalSettings.php
107 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
108 self
::appendUserModules( $this->mQueryPropModules
, $wgAPIPropModules );
109 self
::appendUserModules( $this->mQueryListModules
, $wgAPIListModules );
110 self
::appendUserModules( $this->mQueryMetaModules
, $wgAPIMetaModules );
112 $this->mPropModuleNames
= array_keys( $this->mQueryPropModules
);
113 $this->mListModuleNames
= array_keys( $this->mQueryListModules
);
114 $this->mMetaModuleNames
= array_keys( $this->mQueryMetaModules
);
116 // Allow the entire list of modules at first,
117 // but during module instantiation check if it can be used as a generator.
118 $this->mAllowedGenerators
= array_merge( $this->mListModuleNames
, $this->mPropModuleNames
);
122 * Helper function to append any add-in modules to the list
123 * @param $modules array Module array
124 * @param $newModules array Module array to add to $modules
126 private static function appendUserModules( &$modules, $newModules ) {
127 if ( is_array( $newModules ) ) {
128 foreach ( $newModules as $moduleName => $moduleClass ) {
129 $modules[$moduleName] = $moduleClass;
135 * Gets a default slave database connection object
138 public function getDB() {
139 if ( !isset( $this->mSlaveDB
) ) {
140 $this->profileDBIn();
141 $this->mSlaveDB
= wfGetDB( DB_SLAVE
, 'api' );
142 $this->profileDBOut();
144 return $this->mSlaveDB
;
148 * Get the query database connection with the given name.
149 * If no such connection has been requested before, it will be created.
150 * Subsequent calls with the same $name will return the same connection
151 * as the first, regardless of the values of $db and $groups
152 * @param $name string Name to assign to the database connection
153 * @param $db int One of the DB_* constants
154 * @param $groups array Query groups
157 public function getNamedDB( $name, $db, $groups ) {
158 if ( !array_key_exists( $name, $this->mNamedDB
) ) {
159 $this->profileDBIn();
160 $this->mNamedDB
[$name] = wfGetDB( $db, $groups );
161 $this->profileDBOut();
163 return $this->mNamedDB
[$name];
167 * Gets the set of pages the user has requested (or generated)
170 public function getPageSet() {
171 return $this->mPageSet
;
175 * Get the array mapping module names to class names
176 * @return array(modulename => classname)
178 function getModules() {
179 return array_merge( $this->mQueryPropModules
, $this->mQueryListModules
, $this->mQueryMetaModules
);
183 * Get whether the specified module is a prop, list or a meta query module
184 * @param $moduleName string Name of the module to find type for
185 * @return mixed string or null
187 function getModuleType( $moduleName ) {
188 if ( array_key_exists ( $moduleName, $this->mQueryPropModules
) ) {
192 if ( array_key_exists ( $moduleName, $this->mQueryListModules
) ) {
196 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules
) ) {
203 public function getCustomPrinter() {
204 // If &exportnowrap is set, use the raw formatter
205 if ( $this->getParameter( 'export' ) &&
206 $this->getParameter( 'exportnowrap' ) )
208 return new ApiFormatRaw( $this->getMain(),
209 $this->getMain()->createPrinterByName( 'xml' ) );
216 * Query execution happens in the following steps:
217 * #1 Create a PageSet object with any pages requested by the user
218 * #2 If using a generator, execute it to get a new ApiPageSet object
219 * #3 Instantiate all requested modules.
220 * This way the PageSet object will know what shared data is required,
221 * and minimize DB calls.
222 * #4 Output all normalization and redirect resolution information
223 * #5 Execute all requested modules
225 public function execute() {
226 $this->params
= $this->extractRequestParams();
227 $this->redirects
= $this->params
['redirects'];
228 $this->convertTitles
= $this->params
['converttitles'];
231 $this->mPageSet
= new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
233 // Instantiate requested modules
235 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules
);
236 $this->instantiateModules( $modules, 'list', $this->mQueryListModules
);
237 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules
);
239 $cacheMode = 'public';
241 // If given, execute generator to substitute user supplied data with generated data.
242 if ( isset( $this->params
['generator'] ) ) {
243 $generator = $this->newGenerator( $this->params
['generator'] );
244 $params = $generator->extractRequestParams();
245 $cacheMode = $this->mergeCacheMode( $cacheMode,
246 $generator->getCacheMode( $params ) );
247 $this->executeGeneratorModule( $generator, $modules );
249 // Append custom fields and populate page/revision information
250 $this->addCustomFldsToPageSet( $modules, $this->mPageSet
);
251 $this->mPageSet
->execute();
254 // Record page information (title, namespace, if exists, etc)
255 $this->outputGeneralPageInfo();
257 // Execute all requested modules.
258 foreach ( $modules as $module ) {
259 $params = $module->extractRequestParams();
260 $cacheMode = $this->mergeCacheMode(
261 $cacheMode, $module->getCacheMode( $params ) );
262 $module->profileIn();
264 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
265 $module->profileOut();
268 // Set the cache mode
269 $this->getMain()->setCacheMode( $cacheMode );
273 * Update a cache mode string, applying the cache mode of a new module to it.
274 * The cache mode may increase in the level of privacy, but public modules
275 * added to private data do not decrease the level of privacy.
277 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
278 if ( $modCacheMode === 'anon-public-user-private' ) {
279 if ( $cacheMode !== 'private' ) {
280 $cacheMode = 'anon-public-user-private';
282 } elseif ( $modCacheMode === 'public' ) {
283 // do nothing, if it's public already it will stay public
285 $cacheMode = 'private';
291 * Query modules may optimize data requests through the $this->getPageSet() object
292 * by adding extra fields from the page table.
293 * This function will gather all the extra request fields from the modules.
294 * @param $modules array of module objects
295 * @param $pageSet ApiPageSet
297 private function addCustomFldsToPageSet( $modules, $pageSet ) {
298 // Query all requested modules.
299 foreach ( $modules as $module ) {
300 $module->requestExtraData( $pageSet );
305 * Create instances of all modules requested by the client
306 * @param $modules Array to append instantiated modules to
307 * @param $param string Parameter name to read modules from
308 * @param $moduleList Array array(modulename => classname)
310 private function instantiateModules( &$modules, $param, $moduleList ) {
311 $list = @$this->params
[$param];
312 if ( !is_null ( $list ) ) {
313 foreach ( $list as $moduleName ) {
314 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
320 * Appends an element for each page in the current pageSet with the
321 * most general information (id, title), plus any title normalizations
322 * and missing or invalid title/pageids/revids.
324 private function outputGeneralPageInfo() {
325 $pageSet = $this->getPageSet();
326 $result = $this->getResult();
328 // We don't check for a full result set here because we can't be adding
329 // more than 380K. The maximum revision size is in the megabyte range,
330 // and the maximum result size must be even higher than that.
332 // Title normalizations
333 $normValues = array();
334 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
335 $normValues[] = array(
336 'from' => $rawTitleStr,
341 if ( count( $normValues ) ) {
342 $result->setIndexedTagName( $normValues, 'n' );
343 $result->addValue( 'query', 'normalized', $normValues );
347 $convValues = array();
348 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
349 $convValues[] = array(
350 'from' => $rawTitleStr,
355 if ( count( $convValues ) ) {
356 $result->setIndexedTagName( $convValues, 'c' );
357 $result->addValue( 'query', 'converted', $convValues );
361 $intrwValues = array();
362 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
363 $intrwValues[] = array(
364 'title' => $rawTitleStr,
365 'iw' => $interwikiStr
369 if ( count( $intrwValues ) ) {
370 $result->setIndexedTagName( $intrwValues, 'i' );
371 $result->addValue( 'query', 'interwiki', $intrwValues );
374 // Show redirect information
375 $redirValues = array();
376 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
377 $redirValues[] = array(
378 'from' => strval( $titleStrFrom ),
383 if ( count( $redirValues ) ) {
384 $result->setIndexedTagName( $redirValues, 'r' );
385 $result->addValue( 'query', 'redirects', $redirValues );
388 // Missing revision elements
389 $missingRevIDs = $pageSet->getMissingRevisionIDs();
390 if ( count( $missingRevIDs ) ) {
392 foreach ( $missingRevIDs as $revid ) {
393 $revids[$revid] = array(
397 $result->setIndexedTagName( $revids, 'rev' );
398 $result->addValue( 'query', 'badrevids', $revids );
404 // Report any missing titles
405 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
407 ApiQueryBase
::addTitleInfo( $vals, $title );
408 $vals['missing'] = '';
409 $pages[$fakeId] = $vals;
411 // Report any invalid titles
412 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
413 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
415 // Report any missing page ids
416 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
417 $pages[$pageid] = array(
422 // Report special pages
423 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
425 ApiQueryBase
::addTitleInfo( $vals, $title );
426 $vals['special'] = '';
427 if ( $title->getNamespace() == NS_SPECIAL
&&
428 !SpecialPage
::exists( $title->getText() ) ) {
429 $vals['missing'] = '';
430 } elseif ( $title->getNamespace() == NS_MEDIA
&&
431 !wfFindFile( $title ) ) {
432 $vals['missing'] = '';
434 $pages[$fakeId] = $vals;
437 // Output general page information for found titles
438 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
440 $vals['pageid'] = $pageid;
441 ApiQueryBase
::addTitleInfo( $vals, $title );
442 $pages[$pageid] = $vals;
445 if ( count( $pages ) ) {
446 if ( $this->params
['indexpageids'] ) {
447 $pageIDs = array_keys( $pages );
448 // json treats all map keys as strings - converting to match
449 $pageIDs = array_map( 'strval', $pageIDs );
450 $result->setIndexedTagName( $pageIDs, 'id' );
451 $result->addValue( 'query', 'pageids', $pageIDs );
454 $result->setIndexedTagName( $pages, 'page' );
455 $result->addValue( 'query', 'pages', $pages );
457 if ( $this->params
['export'] ) {
458 $this->doExport( $pageSet, $result );
463 * @param $pageSet ApiPageSet Pages to be exported
464 * @param $result ApiResult Result to output to
466 private function doExport( $pageSet, $result ) {
467 $exportTitles = array();
468 $titles = $pageSet->getGoodTitles();
469 if( count( $titles ) ) {
470 foreach ( $titles as $title ) {
471 if ( $title->userCanRead() ) {
472 $exportTitles[] = $title;
476 // only export when there are titles
477 if ( !count( $exportTitles ) ) {
481 $exporter = new WikiExporter( $this->getDB() );
482 // WikiExporter writes to stdout, so catch its
485 $exporter->openStream();
486 foreach ( $exportTitles as $title ) {
487 $exporter->pageByTitle( $title );
489 $exporter->closeStream();
490 $exportxml = ob_get_contents();
493 // Don't check the size of exported stuff
494 // It's not continuable, so it would cause more
495 // problems than it'd solve
496 $result->disableSizeCheck();
497 if ( $this->params
['exportnowrap'] ) {
499 // Raw formatter will handle this
500 $result->addValue( null, 'text', $exportxml );
501 $result->addValue( null, 'mime', 'text/xml' );
504 ApiResult
::setContent( $r, $exportxml );
505 $result->addValue( 'query', 'export', $r );
507 $result->enableSizeCheck();
511 * Create a generator object of the given type and return it
512 * @param $generatorName string Module name
513 * @return ApiQueryGeneratorBase
515 public function newGenerator( $generatorName ) {
516 // Find class that implements requested generator
517 if ( isset( $this->mQueryListModules
[$generatorName] ) ) {
518 $className = $this->mQueryListModules
[$generatorName];
519 } elseif ( isset( $this->mQueryPropModules
[$generatorName] ) ) {
520 $className = $this->mQueryPropModules
[$generatorName];
522 ApiBase
::dieDebug( __METHOD__
, "Unknown generator=$generatorName" );
524 $generator = new $className ( $this, $generatorName );
525 if ( !$generator instanceof ApiQueryGeneratorBase
) {
526 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
528 $generator->setGeneratorMode();
533 * For generator mode, execute generator, and use its output as new
535 * @param $generator ApiQueryGeneratorBase Generator Module
536 * @param $modules array of module objects
538 protected function executeGeneratorModule( $generator, $modules ) {
540 $resultPageSet = new ApiPageSet( $this, $this->redirects
, $this->convertTitles
);
542 // Add any additional fields modules may need
543 $generator->requestExtraData( $this->mPageSet
);
544 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
546 // Populate page information with the original user input
547 $this->mPageSet
->execute();
549 // populate resultPageSet with the generator output
550 $generator->profileIn();
551 $generator->executeGenerator( $resultPageSet );
552 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
553 $resultPageSet->finishPageSetGeneration();
554 $generator->profileOut();
556 // Swap the resulting pageset back in
557 $this->mPageSet
= $resultPageSet;
560 public function getAllowedParams() {
563 ApiBase
::PARAM_ISMULTI
=> true,
564 ApiBase
::PARAM_TYPE
=> $this->mPropModuleNames
567 ApiBase
::PARAM_ISMULTI
=> true,
568 ApiBase
::PARAM_TYPE
=> $this->mListModuleNames
571 ApiBase
::PARAM_ISMULTI
=> true,
572 ApiBase
::PARAM_TYPE
=> $this->mMetaModuleNames
574 'generator' => array(
575 ApiBase
::PARAM_TYPE
=> $this->mAllowedGenerators
577 'redirects' => false,
578 'converttitles' => false,
579 'indexpageids' => false,
581 'exportnowrap' => false,
586 * Override the parent to generate help messages for all available query modules.
589 public function makeHelpMsg() {
592 // Make sure the internal object is empty
593 // (just in case a sub-module decides to optimize during instantiation)
594 $this->mPageSet
= null;
595 $this->mAllowedGenerators
= array(); // Will be repopulated
597 $querySeparator = str_repeat( '--- ', 8 );
598 $moduleSeparator = str_repeat( '*** ', 10 );
599 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
600 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules
, 'prop' );
601 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
602 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules
, 'list' );
603 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
604 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules
, 'meta' );
605 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
607 // Perform the base call last because the $this->mAllowedGenerators
608 // will be updated inside makeHelpMsgHelper()
609 // Use parent to make default message for the query module
610 $msg = parent
::makeHelpMsg() . $msg;
616 * For all modules in $moduleList, generate help messages and join them together
617 * @param $moduleList Array array(modulename => classname)
618 * @param $paramName string Parameter name
621 private function makeHelpMsgHelper( $moduleList, $paramName ) {
622 $moduleDescriptions = array();
624 foreach ( $moduleList as $moduleName => $moduleClass ) {
625 $module = new $moduleClass ( $this, $moduleName, null );
627 $msg = ApiMain
::makeHelpMsgHeader( $module, $paramName );
628 $msg2 = $module->makeHelpMsg();
629 if ( $msg2 !== false ) {
632 if ( $module instanceof ApiQueryGeneratorBase
) {
633 $this->mAllowedGenerators
[] = $moduleName;
634 $msg .= "Generator:\n This module may be used as a generator\n";
636 $moduleDescriptions[] = $msg;
639 return implode( "\n", $moduleDescriptions );
643 * Override to add extra parameters from PageSet
646 public function makeHelpMsgParameters() {
647 $psModule = new ApiPageSet( $this );
648 return $psModule->makeHelpMsgParameters() . parent
::makeHelpMsgParameters();
651 public function shouldCheckMaxlag() {
655 public function getParamDescription() {
657 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
658 'list' => 'Which lists to get. Module help is available below',
659 'meta' => 'Which metadata to get about the site. Module help is available below',
660 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
661 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
662 'redirects' => 'Automatically resolve redirects',
663 'converttitles' => array( "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
664 'Languages that support variant conversion include kk, ku, gan, tg, sr, zh' ),
665 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
666 'export' => 'Export the current revisions of all given or generated pages',
667 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
671 public function getDescription() {
673 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
674 'and is loosely based on the old query.php interface.',
675 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
679 public function getPossibleErrors() {
680 return array_merge( parent
::getPossibleErrors(), array(
681 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
685 protected function getExamples() {
687 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
688 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
692 public function getVersion() {
693 $psModule = new ApiPageSet( $this );
695 $vers[] = __CLASS__
. ': $Id$';
696 $vers[] = $psModule->getVersion();