re r66702 Use wfMsgForContent instead of wfMsg
[lhc/web/wiklou.git] / includes / api / ApiQuery.php
1 <?php
2
3 /**
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
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.
36 *
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.
39 *
40 * @ingroup API
41 */
42 class ApiQuery extends ApiBase {
43
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
46 private $params, $redirect;
47
48 private $mQueryPropModules = array(
49 'info' => 'ApiQueryInfo',
50 'revisions' => 'ApiQueryRevisions',
51 'links' => 'ApiQueryLinks',
52 'iwlinks' => 'ApiQueryIWLinks',
53 'langlinks' => 'ApiQueryLangLinks',
54 'images' => 'ApiQueryImages',
55 'imageinfo' => 'ApiQueryImageInfo',
56 'templates' => 'ApiQueryLinks',
57 'categories' => 'ApiQueryCategories',
58 'extlinks' => 'ApiQueryExternalLinks',
59 'categoryinfo' => 'ApiQueryCategoryInfo',
60 'duplicatefiles' => 'ApiQueryDuplicateFiles',
61 );
62
63 private $mQueryListModules = array(
64 'allimages' => 'ApiQueryAllimages',
65 'allpages' => 'ApiQueryAllpages',
66 'alllinks' => 'ApiQueryAllLinks',
67 'allcategories' => 'ApiQueryAllCategories',
68 'allusers' => 'ApiQueryAllUsers',
69 'backlinks' => 'ApiQueryBacklinks',
70 'blocks' => 'ApiQueryBlocks',
71 'categorymembers' => 'ApiQueryCategoryMembers',
72 'deletedrevs' => 'ApiQueryDeletedrevs',
73 'embeddedin' => 'ApiQueryBacklinks',
74 'filearchive' => 'ApiQueryFilearchive',
75 'imageusage' => 'ApiQueryBacklinks',
76 'logevents' => 'ApiQueryLogEvents',
77 'recentchanges' => 'ApiQueryRecentChanges',
78 'search' => 'ApiQuerySearch',
79 'tags' => 'ApiQueryTags',
80 'usercontribs' => 'ApiQueryContributions',
81 'watchlist' => 'ApiQueryWatchlist',
82 'watchlistraw' => 'ApiQueryWatchlistRaw',
83 'exturlusage' => 'ApiQueryExtLinksUsage',
84 'users' => 'ApiQueryUsers',
85 'random' => 'ApiQueryRandom',
86 'protectedtitles' => 'ApiQueryProtectedTitles',
87 );
88
89 private $mQueryMetaModules = array(
90 'siteinfo' => 'ApiQuerySiteinfo',
91 'userinfo' => 'ApiQueryUserInfo',
92 'allmessages' => 'ApiQueryAllmessages',
93 );
94
95 private $mSlaveDB = null;
96 private $mNamedDB = array();
97
98 public function __construct( $main, $action ) {
99 parent::__construct( $main, $action );
100
101 // Allow custom modules to be added in LocalSettings.php
102 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
103 self::appendUserModules( $this->mQueryPropModules, $wgAPIPropModules );
104 self::appendUserModules( $this->mQueryListModules, $wgAPIListModules );
105 self::appendUserModules( $this->mQueryMetaModules, $wgAPIMetaModules );
106
107 $this->mPropModuleNames = array_keys( $this->mQueryPropModules );
108 $this->mListModuleNames = array_keys( $this->mQueryListModules );
109 $this->mMetaModuleNames = array_keys( $this->mQueryMetaModules );
110
111 // Allow the entire list of modules at first,
112 // but during module instantiation check if it can be used as a generator.
113 $this->mAllowedGenerators = array_merge( $this->mListModuleNames, $this->mPropModuleNames );
114 }
115
116 /**
117 * Helper function to append any add-in modules to the list
118 * @param $modules array Module array
119 * @param $newModules array Module array to add to $modules
120 */
121 private static function appendUserModules( &$modules, $newModules ) {
122 if ( is_array( $newModules ) ) {
123 foreach ( $newModules as $moduleName => $moduleClass ) {
124 $modules[$moduleName] = $moduleClass;
125 }
126 }
127 }
128
129 /**
130 * Gets a default slave database connection object
131 * @return Database
132 */
133 public function getDB() {
134 if ( !isset( $this->mSlaveDB ) ) {
135 $this->profileDBIn();
136 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
137 $this->profileDBOut();
138 }
139 return $this->mSlaveDB;
140 }
141
142 /**
143 * Get the query database connection with the given name.
144 * If no such connection has been requested before, it will be created.
145 * Subsequent calls with the same $name will return the same connection
146 * as the first, regardless of the values of $db and $groups
147 * @param $name string Name to assign to the database connection
148 * @param $db int One of the DB_* constants
149 * @param $groups array Query groups
150 * @return Database
151 */
152 public function getNamedDB( $name, $db, $groups ) {
153 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
154 $this->profileDBIn();
155 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
156 $this->profileDBOut();
157 }
158 return $this->mNamedDB[$name];
159 }
160
161 /**
162 * Gets the set of pages the user has requested (or generated)
163 * @return ApiPageSet
164 */
165 public function getPageSet() {
166 return $this->mPageSet;
167 }
168
169 /**
170 * Get the array mapping module names to class names
171 * @return array(modulename => classname)
172 */
173 function getModules() {
174 return array_merge( $this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules );
175 }
176
177 /**
178 * Get whether the specified module is a prop, list or a meta query module
179 * @param $moduleName string Name of the module to find type for
180 * @return mixed string or null
181 */
182 function getModuleType( $moduleName ) {
183 if ( array_key_exists ( $moduleName, $this->mQueryPropModules ) ) {
184 return 'prop';
185 }
186
187 if ( array_key_exists ( $moduleName, $this->mQueryListModules ) ) {
188 return 'list';
189 }
190
191 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules ) ) {
192 return 'meta';
193 }
194
195 return null;
196 }
197
198 public function getCustomPrinter() {
199 // If &exportnowrap is set, use the raw formatter
200 if ( $this->getParameter( 'export' ) &&
201 $this->getParameter( 'exportnowrap' ) )
202 {
203 return new ApiFormatRaw( $this->getMain(),
204 $this->getMain()->createPrinterByName( 'xml' ) );
205 } else {
206 return null;
207 }
208 }
209
210 /**
211 * Query execution happens in the following steps:
212 * #1 Create a PageSet object with any pages requested by the user
213 * #2 If using a generator, execute it to get a new ApiPageSet object
214 * #3 Instantiate all requested modules.
215 * This way the PageSet object will know what shared data is required,
216 * and minimize DB calls.
217 * #4 Output all normalization and redirect resolution information
218 * #5 Execute all requested modules
219 */
220 public function execute() {
221 $this->params = $this->extractRequestParams();
222 $this->redirects = $this->params['redirects'];
223
224 // Create PageSet
225 $this->mPageSet = new ApiPageSet( $this, $this->redirects );
226
227 // Instantiate requested modules
228 $modules = array();
229 $this->InstantiateModules( $modules, 'prop', $this->mQueryPropModules );
230 $this->InstantiateModules( $modules, 'list', $this->mQueryListModules );
231 $this->InstantiateModules( $modules, 'meta', $this->mQueryMetaModules );
232
233 // If given, execute generator to substitute user supplied data with generated data.
234 if ( isset( $this->params['generator'] ) ) {
235 $this->executeGeneratorModule( $this->params['generator'], $modules );
236 } else {
237 // Append custom fields and populate page/revision information
238 $this->addCustomFldsToPageSet( $modules, $this->mPageSet );
239 $this->mPageSet->execute();
240 }
241
242 // Record page information (title, namespace, if exists, etc)
243 $this->outputGeneralPageInfo();
244
245 // Execute all requested modules.
246 foreach ( $modules as $module ) {
247 $module->profileIn();
248 $module->execute();
249 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
250 $module->profileOut();
251 }
252 }
253
254 /**
255 * Query modules may optimize data requests through the $this->getPageSet() object
256 * by adding extra fields from the page table.
257 * This function will gather all the extra request fields from the modules.
258 * @param $modules array of module objects
259 * @param $pageSet ApiPageSet
260 */
261 private function addCustomFldsToPageSet( $modules, $pageSet ) {
262 // Query all requested modules.
263 foreach ( $modules as $module ) {
264 $module->requestExtraData( $pageSet );
265 }
266 }
267
268 /**
269 * Create instances of all modules requested by the client
270 * @param $modules array to append instatiated modules to
271 * @param $param string Parameter name to read modules from
272 * @param $moduleList array(modulename => classname)
273 */
274 private function InstantiateModules( &$modules, $param, $moduleList ) {
275 $list = @$this->params[$param];
276 if ( !is_null ( $list ) ) {
277 foreach ( $list as $moduleName ) {
278 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
279 }
280 }
281 }
282
283 /**
284 * Appends an element for each page in the current pageSet with the
285 * most general information (id, title), plus any title normalizations
286 * and missing or invalid title/pageids/revids.
287 */
288 private function outputGeneralPageInfo() {
289 $pageSet = $this->getPageSet();
290 $result = $this->getResult();
291
292 // We don't check for a full result set here because we can't be adding
293 // more than 380K. The maximum revision size is in the megabyte range,
294 // and the maximum result size must be even higher than that.
295
296 // Title normalizations
297 $normValues = array();
298 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
299 $normValues[] = array(
300 'from' => $rawTitleStr,
301 'to' => $titleStr
302 );
303 }
304
305 if ( count( $normValues ) ) {
306 $result->setIndexedTagName( $normValues, 'n' );
307 $result->addValue( 'query', 'normalized', $normValues );
308 }
309
310 // Interwiki titles
311 $intrwValues = array();
312 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
313 $intrwValues[] = array(
314 'title' => $rawTitleStr,
315 'iw' => $interwikiStr
316 );
317 }
318
319 if ( count( $intrwValues ) ) {
320 $result->setIndexedTagName( $intrwValues, 'i' );
321 $result->addValue( 'query', 'interwiki', $intrwValues );
322 }
323
324 // Show redirect information
325 $redirValues = array();
326 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
327 $redirValues[] = array(
328 'from' => strval( $titleStrFrom ),
329 'to' => $titleStrTo
330 );
331 }
332
333 if ( count( $redirValues ) ) {
334 $result->setIndexedTagName( $redirValues, 'r' );
335 $result->addValue( 'query', 'redirects', $redirValues );
336 }
337
338 //
339 // Missing revision elements
340 //
341 $missingRevIDs = $pageSet->getMissingRevisionIDs();
342 if ( count( $missingRevIDs ) ) {
343 $revids = array();
344 foreach ( $missingRevIDs as $revid ) {
345 $revids[$revid] = array(
346 'revid' => $revid
347 );
348 }
349 $result->setIndexedTagName( $revids, 'rev' );
350 $result->addValue( 'query', 'badrevids', $revids );
351 }
352
353 //
354 // Page elements
355 //
356 $pages = array();
357
358 // Report any missing titles
359 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
360 $vals = array();
361 ApiQueryBase::addTitleInfo( $vals, $title );
362 $vals['missing'] = '';
363 $pages[$fakeId] = $vals;
364 }
365 // Report any invalid titles
366 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
367 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
368 }
369 // Report any missing page ids
370 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
371 $pages[$pageid] = array(
372 'pageid' => $pageid,
373 'missing' => ''
374 );
375 }
376
377 // Output general page information for found titles
378 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
379 $vals = array();
380 $vals['pageid'] = $pageid;
381 ApiQueryBase::addTitleInfo( $vals, $title );
382 $pages[$pageid] = $vals;
383 }
384
385 if ( count( $pages ) ) {
386 if ( $this->params['indexpageids'] ) {
387 $pageIDs = array_keys( $pages );
388 // json treats all map keys as strings - converting to match
389 $pageIDs = array_map( 'strval', $pageIDs );
390 $result->setIndexedTagName( $pageIDs, 'id' );
391 $result->addValue( 'query', 'pageids', $pageIDs );
392 }
393
394 $result->setIndexedTagName( $pages, 'page' );
395 $result->addValue( 'query', 'pages', $pages );
396 }
397 if ( $this->params['export'] ) {
398 $exporter = new WikiExporter( $this->getDB() );
399 // WikiExporter writes to stdout, so catch its
400 // output with an ob
401 ob_start();
402 $exporter->openStream();
403 foreach ( @$pageSet->getGoodTitles() as $title ) {
404 if ( $title->userCanRead() ) {
405 $exporter->pageByTitle( $title );
406 }
407 }
408 $exporter->closeStream();
409 $exportxml = ob_get_contents();
410 ob_end_clean();
411
412 // Don't check the size of exported stuff
413 // It's not continuable, so it would cause more
414 // problems than it'd solve
415 $result->disableSizeCheck();
416 if ( $this->params['exportnowrap'] ) {
417 $result->reset();
418 // Raw formatter will handle this
419 $result->addValue( null, 'text', $exportxml );
420 $result->addValue( null, 'mime', 'text/xml' );
421 } else {
422 $r = array();
423 ApiResult::setContent( $r, $exportxml );
424 $result->addValue( 'query', 'export', $r );
425 }
426 $result->enableSizeCheck();
427 }
428 }
429
430 /**
431 * For generator mode, execute generator, and use its output as new
432 * ApiPageSet
433 * @param $generatorName string Module name
434 * @param $modules array of module objects
435 */
436 protected function executeGeneratorModule( $generatorName, $modules ) {
437 // Find class that implements requested generator
438 if ( isset( $this->mQueryListModules[$generatorName] ) ) {
439 $className = $this->mQueryListModules[$generatorName];
440 } elseif ( isset( $this->mQueryPropModules[$generatorName] ) ) {
441 $className = $this->mQueryPropModules[$generatorName];
442 } else {
443 ApiBase::dieDebug( __METHOD__, "Unknown generator=$generatorName" );
444 }
445
446 // Generator results
447 $resultPageSet = new ApiPageSet( $this, $this->redirects );
448
449 // Create and execute the generator
450 $generator = new $className ( $this, $generatorName );
451 if ( !$generator instanceof ApiQueryGeneratorBase ) {
452 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
453 }
454
455 $generator->setGeneratorMode();
456
457 // Add any additional fields modules may need
458 $generator->requestExtraData( $this->mPageSet );
459 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
460
461 // Populate page information with the original user input
462 $this->mPageSet->execute();
463
464 // populate resultPageSet with the generator output
465 $generator->profileIn();
466 $generator->executeGenerator( $resultPageSet );
467 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
468 $resultPageSet->finishPageSetGeneration();
469 $generator->profileOut();
470
471 // Swap the resulting pageset back in
472 $this->mPageSet = $resultPageSet;
473 }
474
475 public function getAllowedParams() {
476 return array(
477 'prop' => array(
478 ApiBase::PARAM_ISMULTI => true,
479 ApiBase::PARAM_TYPE => $this->mPropModuleNames
480 ),
481 'list' => array(
482 ApiBase::PARAM_ISMULTI => true,
483 ApiBase::PARAM_TYPE => $this->mListModuleNames
484 ),
485 'meta' => array(
486 ApiBase::PARAM_ISMULTI => true,
487 ApiBase::PARAM_TYPE => $this->mMetaModuleNames
488 ),
489 'generator' => array(
490 ApiBase::PARAM_TYPE => $this->mAllowedGenerators
491 ),
492 'redirects' => false,
493 'indexpageids' => false,
494 'export' => false,
495 'exportnowrap' => false,
496 );
497 }
498
499 /**
500 * Override the parent to generate help messages for all available query modules.
501 * @return string
502 */
503 public function makeHelpMsg() {
504 $msg = '';
505
506 // Make sure the internal object is empty
507 // (just in case a sub-module decides to optimize during instantiation)
508 $this->mPageSet = null;
509 $this->mAllowedGenerators = array(); // Will be repopulated
510
511 $astriks = str_repeat( '--- ', 8 );
512 $astriks2 = str_repeat( '*** ', 10 );
513 $msg .= "\n$astriks Query: Prop $astriks\n\n";
514 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules, 'prop' );
515 $msg .= "\n$astriks Query: List $astriks\n\n";
516 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules, 'list' );
517 $msg .= "\n$astriks Query: Meta $astriks\n\n";
518 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules, 'meta' );
519 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
520
521 // Perform the base call last because the $this->mAllowedGenerators
522 // will be updated inside makeHelpMsgHelper()
523 // Use parent to make default message for the query module
524 $msg = parent::makeHelpMsg() . $msg;
525
526 return $msg;
527 }
528
529 /**
530 * For all modules in $moduleList, generate help messages and join them together
531 * @param $moduleList array(modulename => classname)
532 * @param $paramName string Parameter name
533 * @return string
534 */
535 private function makeHelpMsgHelper( $moduleList, $paramName ) {
536 $moduleDescriptions = array();
537
538 foreach ( $moduleList as $moduleName => $moduleClass ) {
539 $module = new $moduleClass ( $this, $moduleName, null );
540
541 $msg = ApiMain::makeHelpMsgHeader( $module, $paramName );
542 $msg2 = $module->makeHelpMsg();
543 if ( $msg2 !== false ) {
544 $msg .= $msg2;
545 }
546 if ( $module instanceof ApiQueryGeneratorBase ) {
547 $this->mAllowedGenerators[] = $moduleName;
548 $msg .= "Generator:\n This module may be used as a generator\n";
549 }
550 $moduleDescriptions[] = $msg;
551 }
552
553 return implode( "\n", $moduleDescriptions );
554 }
555
556 /**
557 * Override to add extra parameters from PageSet
558 * @return string
559 */
560 public function makeHelpMsgParameters() {
561 $psModule = new ApiPageSet( $this );
562 return $psModule->makeHelpMsgParameters() . parent::makeHelpMsgParameters();
563 }
564
565 public function shouldCheckMaxlag() {
566 return true;
567 }
568
569 public function getParamDescription() {
570 return array(
571 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
572 'list' => 'Which lists to get. Module help is available below',
573 'meta' => 'Which metadata to get about the site. Module help is available below',
574 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
575 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
576 'redirects' => 'Automatically resolve redirects',
577 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
578 'export' => 'Export the current revisions of all given or generated pages',
579 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
580 );
581 }
582
583 public function getDescription() {
584 return array(
585 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
586 'and is loosely based on the old query.php interface.',
587 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
588 );
589 }
590
591 public function getPossibleErrors() {
592 return array_merge( parent::getPossibleErrors(), array(
593 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
594 ) );
595 }
596
597 protected function getExamples() {
598 return array(
599 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
600 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
601 );
602 }
603
604 public function getVersion() {
605 $psModule = new ApiPageSet( $this );
606 $vers = array();
607 $vers[] = __CLASS__ . ': $Id$';
608 $vers[] = $psModule->getVersion();
609 return $vers;
610 }
611 }