Correct empty case for r49149
[mediawiki.git] / includes / api / ApiQuery.php
blobe3719e0d506f35e113cc8d18bcc58bf5b0bfb4fb
1 <?php
3 /*
4 * Created on Sep 7, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
31 /**
32 * This is the main query class. It behaves similar to ApiMain: based on the
33 * parameters given, it will create a list of titles to work on (an ApiPageSet
34 * object), instantiate and execute various property/list/meta modules, and
35 * assemble all resulting data into a single ApiResult object.
37 * In generator mode, a generator will be executed first to populate a second
38 * ApiPageSet object, and that object will be used for all subsequent modules.
40 * @ingroup API
42 class ApiQuery extends ApiBase {
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
46 private $params, $redirect;
48 private $mQueryPropModules = array (
49 'info' => 'ApiQueryInfo',
50 'revisions' => 'ApiQueryRevisions',
51 'links' => 'ApiQueryLinks',
52 'langlinks' => 'ApiQueryLangLinks',
53 'images' => 'ApiQueryImages',
54 'imageinfo' => 'ApiQueryImageInfo',
55 'templates' => 'ApiQueryLinks',
56 'categories' => 'ApiQueryCategories',
57 'extlinks' => 'ApiQueryExternalLinks',
58 'categoryinfo' => 'ApiQueryCategoryInfo',
59 'duplicatefiles' => 'ApiQueryDuplicateFiles',
62 private $mQueryListModules = array (
63 'allimages' => 'ApiQueryAllimages',
64 'allpages' => 'ApiQueryAllpages',
65 'alllinks' => 'ApiQueryAllLinks',
66 'allcategories' => 'ApiQueryAllCategories',
67 'allusers' => 'ApiQueryAllUsers',
68 'backlinks' => 'ApiQueryBacklinks',
69 'blocks' => 'ApiQueryBlocks',
70 'categorymembers' => 'ApiQueryCategoryMembers',
71 'deletedrevs' => 'ApiQueryDeletedrevs',
72 'embeddedin' => 'ApiQueryBacklinks',
73 'imageusage' => 'ApiQueryBacklinks',
74 'logevents' => 'ApiQueryLogEvents',
75 'recentchanges' => 'ApiQueryRecentChanges',
76 'search' => 'ApiQuerySearch',
77 'usercontribs' => 'ApiQueryContributions',
78 'watchlist' => 'ApiQueryWatchlist',
79 'watchlistraw' => 'ApiQueryWatchlistRaw',
80 'exturlusage' => 'ApiQueryExtLinksUsage',
81 'users' => 'ApiQueryUsers',
82 'random' => 'ApiQueryRandom',
83 'protectedtitles' => 'ApiQueryProtectedTitles',
86 private $mQueryMetaModules = array (
87 'siteinfo' => 'ApiQuerySiteinfo',
88 'userinfo' => 'ApiQueryUserInfo',
89 'allmessages' => 'ApiQueryAllmessages',
92 private $mSlaveDB = null;
93 private $mNamedDB = array();
95 public function __construct($main, $action) {
96 parent :: __construct($main, $action);
98 // Allow custom modules to be added in LocalSettings.php
99 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
100 self :: appendUserModules($this->mQueryPropModules, $wgAPIPropModules);
101 self :: appendUserModules($this->mQueryListModules, $wgAPIListModules);
102 self :: appendUserModules($this->mQueryMetaModules, $wgAPIMetaModules);
104 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
105 $this->mListModuleNames = array_keys($this->mQueryListModules);
106 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
108 // Allow the entire list of modules at first,
109 // but during module instantiation check if it can be used as a generator.
110 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
114 * Helper function to append any add-in modules to the list
115 * @param $modules array Module array
116 * @param $newModules array Module array to add to $modules
118 private static function appendUserModules(&$modules, $newModules) {
119 if (is_array( $newModules )) {
120 foreach ( $newModules as $moduleName => $moduleClass) {
121 $modules[$moduleName] = $moduleClass;
127 * Gets a default slave database connection object
128 * @return Database
130 public function getDB() {
131 if (!isset ($this->mSlaveDB)) {
132 $this->profileDBIn();
133 $this->mSlaveDB = wfGetDB(DB_SLAVE,'api');
134 $this->profileDBOut();
136 return $this->mSlaveDB;
140 * Get the query database connection with the given name.
141 * If no such connection has been requested before, it will be created.
142 * Subsequent calls with the same $name will return the same connection
143 * as the first, regardless of the values of $db and $groups
144 * @param $name string Name to assign to the database connection
145 * @param $db int One of the DB_* constants
146 * @param $groups array Query groups
147 * @return Database
149 public function getNamedDB($name, $db, $groups) {
150 if (!array_key_exists($name, $this->mNamedDB)) {
151 $this->profileDBIn();
152 $this->mNamedDB[$name] = wfGetDB($db, $groups);
153 $this->profileDBOut();
155 return $this->mNamedDB[$name];
159 * Gets the set of pages the user has requested (or generated)
160 * @return ApiPageSet
162 public function getPageSet() {
163 return $this->mPageSet;
167 * Get the array mapping module names to class names
168 * @return array(modulename => classname)
170 function getModules() {
171 return array_merge($this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules);
174 public function getCustomPrinter() {
175 // If &exportnowrap is set, use the raw formatter
176 if ($this->getParameter('export') &&
177 $this->getParameter('exportnowrap'))
178 return new ApiFormatRaw($this->getMain(),
179 $this->getMain()->createPrinterByName('xml'));
180 else
181 return null;
185 * Query execution happens in the following steps:
186 * #1 Create a PageSet object with any pages requested by the user
187 * #2 If using a generator, execute it to get a new ApiPageSet object
188 * #3 Instantiate all requested modules.
189 * This way the PageSet object will know what shared data is required,
190 * and minimize DB calls.
191 * #4 Output all normalization and redirect resolution information
192 * #5 Execute all requested modules
194 public function execute() {
196 $this->params = $this->extractRequestParams();
197 $this->redirects = $this->params['redirects'];
200 // Create PageSet
202 $this->mPageSet = new ApiPageSet($this, $this->redirects);
205 // Instantiate requested modules
207 $modules = array ();
208 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
209 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
210 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
213 // If given, execute generator to substitute user supplied data with generated data.
215 if (isset ($this->params['generator'])) {
216 $this->executeGeneratorModule($this->params['generator'], $modules);
217 } else {
218 // Append custom fields and populate page/revision information
219 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
220 $this->mPageSet->execute();
224 // Record page information (title, namespace, if exists, etc)
226 $this->outputGeneralPageInfo();
229 // Execute all requested modules.
231 foreach ($modules as $module) {
232 $module->profileIn();
233 $module->execute();
234 wfRunHooks('APIQueryAfterExecute', array(&$module));
235 $module->profileOut();
240 * Query modules may optimize data requests through the $this->getPageSet() object
241 * by adding extra fields from the page table.
242 * This function will gather all the extra request fields from the modules.
243 * @param $modules array of module objects
244 * @param $pageSet ApiPageSet
246 private function addCustomFldsToPageSet($modules, $pageSet) {
247 // Query all requested modules.
248 foreach ($modules as $module) {
249 $module->requestExtraData($pageSet);
254 * Create instances of all modules requested by the client
255 * @param $modules array to append instatiated modules to
256 * @param $param string Parameter name to read modules from
257 * @param $moduleList array(modulename => classname)
259 private function InstantiateModules(&$modules, $param, $moduleList) {
260 $list = @$this->params[$param];
261 if (!is_null ($list))
262 foreach ($list as $moduleName)
263 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
267 * Appends an element for each page in the current pageSet with the
268 * most general information (id, title), plus any title normalizations
269 * and missing or invalid title/pageids/revids.
271 private function outputGeneralPageInfo() {
273 $pageSet = $this->getPageSet();
274 $result = $this->getResult();
276 # We don't check for a full result set here because we can't be adding
277 # more than 380K. The maximum revision size is in the megabyte range,
278 # and the maximum result size must be even higher than that.
280 // Title normalizations
281 $normValues = array ();
282 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
283 $normValues[] = array (
284 'from' => $rawTitleStr,
285 'to' => $titleStr
289 if (count($normValues)) {
290 $result->setIndexedTagName($normValues, 'n');
291 $result->addValue('query', 'normalized', $normValues);
294 // Interwiki titles
295 $intrwValues = array ();
296 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
297 $intrwValues[] = array (
298 'title' => $rawTitleStr,
299 'iw' => $interwikiStr
303 if (count($intrwValues)) {
304 $result->setIndexedTagName($intrwValues, 'i');
305 $result->addValue('query', 'interwiki', $intrwValues);
308 // Show redirect information
309 $redirValues = array ();
310 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
311 $redirValues[] = array (
312 'from' => strval($titleStrFrom),
313 'to' => $titleStrTo
317 if (count($redirValues)) {
318 $result->setIndexedTagName($redirValues, 'r');
319 $result->addValue('query', 'redirects', $redirValues);
323 // Missing revision elements
325 $missingRevIDs = $pageSet->getMissingRevisionIDs();
326 if (count($missingRevIDs)) {
327 $revids = array ();
328 foreach ($missingRevIDs as $revid) {
329 $revids[$revid] = array (
330 'revid' => $revid
333 $result->setIndexedTagName($revids, 'rev');
334 $result->addValue('query', 'badrevids', $revids);
338 // Page elements
340 $pages = array ();
342 // Report any missing titles
343 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
344 $vals = array();
345 ApiQueryBase :: addTitleInfo($vals, $title);
346 $vals['missing'] = '';
347 $pages[$fakeId] = $vals;
349 // Report any invalid titles
350 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
351 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
352 // Report any missing page ids
353 foreach ($pageSet->getMissingPageIDs() as $pageid) {
354 $pages[$pageid] = array (
355 'pageid' => $pageid,
356 'missing' => ''
360 // Output general page information for found titles
361 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
362 $vals = array();
363 $vals['pageid'] = $pageid;
364 ApiQueryBase :: addTitleInfo($vals, $title);
365 $pages[$pageid] = $vals;
368 if (count($pages)) {
370 if ($this->params['indexpageids']) {
371 $pageIDs = array_keys($pages);
372 // json treats all map keys as strings - converting to match
373 $pageIDs = array_map('strval', $pageIDs);
374 $result->setIndexedTagName($pageIDs, 'id');
375 $result->addValue('query', 'pageids', $pageIDs);
378 $result->setIndexedTagName($pages, 'page');
379 $result->addValue('query', 'pages', $pages);
381 if ($this->params['export']) {
382 $exporter = new WikiExporter($this->getDB());
383 // WikiExporter writes to stdout, so catch its
384 // output with an ob
385 ob_start();
386 $exporter->openStream();
387 foreach (@$pageSet->getGoodTitles() as $title)
388 if ($title->userCanRead())
389 $exporter->pageByTitle($title);
390 $exporter->closeStream();
391 $exportxml = ob_get_contents();
392 ob_end_clean();
393 // Don't check the size of exported stuff
394 // It's not continuable, so it would cause more
395 // problems than it'd solve
396 $result->disableSizeCheck();
397 if ($this->params['exportnowrap']) {
398 $result->reset();
399 // Raw formatter will handle this
400 $result->addValue(null, 'text', $exportxml);
401 $result->addValue(null, 'mime', 'text/xml');
402 } else {
403 $r = array();
404 ApiResult::setContent($r, $exportxml);
405 $result->addValue('query', 'export', $r);
407 $result->enableSizeCheck();
412 * For generator mode, execute generator, and use its output as new
413 * ApiPageSet
414 * @param $generatorName string Module name
415 * @param $modules array of module objects
417 protected function executeGeneratorModule($generatorName, $modules) {
419 // Find class that implements requested generator
420 if (isset ($this->mQueryListModules[$generatorName])) {
421 $className = $this->mQueryListModules[$generatorName];
422 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
423 $className = $this->mQueryPropModules[$generatorName];
424 } else {
425 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
428 // Generator results
429 $resultPageSet = new ApiPageSet($this, $this->redirects);
431 // Create and execute the generator
432 $generator = new $className ($this, $generatorName);
433 if (!$generator instanceof ApiQueryGeneratorBase)
434 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
436 $generator->setGeneratorMode();
438 // Add any additional fields modules may need
439 $generator->requestExtraData($this->mPageSet);
440 $this->addCustomFldsToPageSet($modules, $resultPageSet);
442 // Populate page information with the original user input
443 $this->mPageSet->execute();
445 // populate resultPageSet with the generator output
446 $generator->profileIn();
447 $generator->executeGenerator($resultPageSet);
448 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
449 $resultPageSet->finishPageSetGeneration();
450 $generator->profileOut();
452 // Swap the resulting pageset back in
453 $this->mPageSet = $resultPageSet;
456 public function getAllowedParams() {
457 return array (
458 'prop' => array (
459 ApiBase :: PARAM_ISMULTI => true,
460 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
462 'list' => array (
463 ApiBase :: PARAM_ISMULTI => true,
464 ApiBase :: PARAM_TYPE => $this->mListModuleNames
466 'meta' => array (
467 ApiBase :: PARAM_ISMULTI => true,
468 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
470 'generator' => array (
471 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
473 'redirects' => false,
474 'indexpageids' => false,
475 'export' => false,
476 'exportnowrap' => false,
481 * Override the parent to generate help messages for all available query modules.
482 * @return string
484 public function makeHelpMsg() {
486 $msg = '';
488 // Make sure the internal object is empty
489 // (just in case a sub-module decides to optimize during instantiation)
490 $this->mPageSet = null;
491 $this->mAllowedGenerators = array(); // Will be repopulated
493 $astriks = str_repeat('--- ', 8);
494 $astriks2 = str_repeat('*** ', 10);
495 $msg .= "\n$astriks Query: Prop $astriks\n\n";
496 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
497 $msg .= "\n$astriks Query: List $astriks\n\n";
498 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
499 $msg .= "\n$astriks Query: Meta $astriks\n\n";
500 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
501 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
503 // Perform the base call last because the $this->mAllowedGenerators
504 // will be updated inside makeHelpMsgHelper()
505 // Use parent to make default message for the query module
506 $msg = parent :: makeHelpMsg() . $msg;
508 return $msg;
512 * For all modules in $moduleList, generate help messages and join them together
513 * @param $moduleList array(modulename => classname)
514 * @param $paramName string Parameter name
515 * @return string
517 private function makeHelpMsgHelper($moduleList, $paramName) {
519 $moduleDescriptions = array ();
521 foreach ($moduleList as $moduleName => $moduleClass) {
522 $module = new $moduleClass ($this, $moduleName, null);
524 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
525 $msg2 = $module->makeHelpMsg();
526 if ($msg2 !== false)
527 $msg .= $msg2;
528 if ($module instanceof ApiQueryGeneratorBase) {
529 $this->mAllowedGenerators[] = $moduleName;
530 $msg .= "Generator:\n This module may be used as a generator\n";
532 $moduleDescriptions[] = $msg;
535 return implode("\n", $moduleDescriptions);
539 * Override to add extra parameters from PageSet
540 * @return string
542 public function makeHelpMsgParameters() {
543 $psModule = new ApiPageSet($this);
544 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
547 public function shouldCheckMaxlag() {
548 return true;
551 public function getParamDescription() {
552 return array (
553 'prop' => 'Which properties to get for the titles/revisions/pageids',
554 'list' => 'Which lists to get',
555 'meta' => 'Which meta data to get about the site',
556 'generator' => array('Use the output of a list as the input for other prop/list/meta items',
557 'NOTE: generator parameter names must be prefixed with a \'g\', see examples.'),
558 'redirects' => 'Automatically resolve redirects',
559 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.',
560 'export' => 'Export the current revisions of all given or generated pages',
561 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
565 public function getDescription() {
566 return array (
567 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
568 'and is loosely based on the old query.php interface.',
569 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
573 protected function getExamples() {
574 return array (
575 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
576 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
580 public function getVersion() {
581 $psModule = new ApiPageSet($this);
582 $vers = array ();
583 $vers[] = __CLASS__ . ': $Id$';
584 $vers[] = $psModule->getVersion();
585 return $vers;