(bug 45017) Check whether this request is a POST before allowing a query module to...
[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 'duplicatefiles' => 'ApiQueryDuplicateFiles',
48 'extlinks' => 'ApiQueryExternalLinks',
49 'images' => 'ApiQueryImages',
50 'imageinfo' => 'ApiQueryImageInfo',
51 'info' => 'ApiQueryInfo',
52 'links' => 'ApiQueryLinks',
53 'iwlinks' => 'ApiQueryIWLinks',
54 'langlinks' => 'ApiQueryLangLinks',
55 'pageprops' => 'ApiQueryPageProps',
56 'revisions' => 'ApiQueryRevisions',
57 'stashimageinfo' => 'ApiQueryStashImageInfo',
58 'templates' => 'ApiQueryLinks',
59 );
60
61 /**
62 * List of Api Query list modules
63 * @var array
64 */
65 private static $QueryListModules = array(
66 'allcategories' => 'ApiQueryAllCategories',
67 'allimages' => 'ApiQueryAllImages',
68 'alllinks' => 'ApiQueryAllLinks',
69 'allpages' => 'ApiQueryAllPages',
70 'alltransclusions' => 'ApiQueryAllLinks',
71 'allusers' => 'ApiQueryAllUsers',
72 'backlinks' => 'ApiQueryBacklinks',
73 'blocks' => 'ApiQueryBlocks',
74 'categorymembers' => 'ApiQueryCategoryMembers',
75 'deletedrevs' => 'ApiQueryDeletedrevs',
76 'embeddedin' => 'ApiQueryBacklinks',
77 'exturlusage' => 'ApiQueryExtLinksUsage',
78 'filearchive' => 'ApiQueryFilearchive',
79 'imageusage' => 'ApiQueryBacklinks',
80 'iwbacklinks' => 'ApiQueryIWBacklinks',
81 'langbacklinks' => 'ApiQueryLangBacklinks',
82 'logevents' => 'ApiQueryLogEvents',
83 'protectedtitles' => 'ApiQueryProtectedTitles',
84 'querypage' => 'ApiQueryQueryPage',
85 'random' => 'ApiQueryRandom',
86 'recentchanges' => 'ApiQueryRecentChanges',
87 'search' => 'ApiQuerySearch',
88 'tags' => 'ApiQueryTags',
89 'usercontribs' => 'ApiQueryContributions',
90 'users' => 'ApiQueryUsers',
91 'watchlist' => 'ApiQueryWatchlist',
92 'watchlistraw' => 'ApiQueryWatchlistRaw',
93 );
94
95 /**
96 * List of Api Query meta modules
97 * @var array
98 */
99 private static $QueryMetaModules = array(
100 'allmessages' => 'ApiQueryAllMessages',
101 'siteinfo' => 'ApiQuerySiteinfo',
102 'userinfo' => 'ApiQueryUserInfo',
103 );
104
105 /**
106 * List of Api Query generator modules
107 * Defined in code, rather than being derived at runtime,
108 * due to performance reasons
109 * @var array
110 */
111 private $mQueryGenerators = array(
112 'allcategories' => 'ApiQueryAllCategories',
113 'allimages' => 'ApiQueryAllImages',
114 'alllinks' => 'ApiQueryAllLinks',
115 'allpages' => 'ApiQueryAllPages',
116 'alltransclusions' => 'ApiQueryAllLinks',
117 'backlinks' => 'ApiQueryBacklinks',
118 'categories' => 'ApiQueryCategories',
119 'categorymembers' => 'ApiQueryCategoryMembers',
120 'duplicatefiles' => 'ApiQueryDuplicateFiles',
121 'embeddedin' => 'ApiQueryBacklinks',
122 'exturlusage' => 'ApiQueryExtLinksUsage',
123 'images' => 'ApiQueryImages',
124 'imageusage' => 'ApiQueryBacklinks',
125 'iwbacklinks' => 'ApiQueryIWBacklinks',
126 'langbacklinks' => 'ApiQueryLangBacklinks',
127 'links' => 'ApiQueryLinks',
128 'protectedtitles' => 'ApiQueryProtectedTitles',
129 'querypage' => 'ApiQueryQueryPage',
130 'random' => 'ApiQueryRandom',
131 'recentchanges' => 'ApiQueryRecentChanges',
132 'search' => 'ApiQuerySearch',
133 'templates' => 'ApiQueryLinks',
134 'watchlist' => 'ApiQueryWatchlist',
135 'watchlistraw' => 'ApiQueryWatchlistRaw',
136 );
137
138 /**
139 * @var ApiPageSet
140 */
141 private $mPageSet;
142
143 private $params;
144 private $iwUrl;
145 private $mNamedDB = array();
146 private $mModuleMgr;
147
148 /**
149 * @param $main ApiMain
150 * @param $action string
151 */
152 public function __construct( $main, $action ) {
153 parent::__construct( $main, $action );
154
155 $this->mModuleMgr = new ApiModuleManager( $this );
156
157 // Allow custom modules to be added in LocalSettings.php
158 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
159 $this->mModuleMgr->addModules( self::$QueryPropModules, 'prop' );
160 $this->mModuleMgr->addModules( $wgAPIPropModules, 'prop' );
161 $this->mModuleMgr->addModules( self::$QueryListModules, 'list' );
162 $this->mModuleMgr->addModules( $wgAPIListModules, 'list' );
163 $this->mModuleMgr->addModules( self::$QueryMetaModules, 'meta' );
164 $this->mModuleMgr->addModules( $wgAPIMetaModules, 'meta' );
165
166 global $wgAPIGeneratorModules;
167 if ( is_array( $wgAPIGeneratorModules ) ) {
168 foreach ( $wgAPIGeneratorModules as $moduleName => $moduleClass ) {
169 $this->mQueryGenerators[$moduleName] = $moduleClass;
170 }
171 }
172
173 // Create PageSet that will process titles/pageids/revids/generator
174 $this->mPageSet = new ApiPageSet( $this );
175 }
176
177 /**
178 * Overrides to return this instance's module manager.
179 * @return ApiModuleManager
180 */
181 public function getModuleManager() {
182 return $this->mModuleMgr;
183 }
184
185 /**
186 * Get the query database connection with the given name.
187 * If no such connection has been requested before, it will be created.
188 * Subsequent calls with the same $name will return the same connection
189 * as the first, regardless of the values of $db and $groups
190 * @param $name string Name to assign to the database connection
191 * @param $db int One of the DB_* constants
192 * @param $groups array Query groups
193 * @return DatabaseBase
194 */
195 public function getNamedDB( $name, $db, $groups ) {
196 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
197 $this->profileDBIn();
198 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
199 $this->profileDBOut();
200 }
201 return $this->mNamedDB[$name];
202 }
203
204 /**
205 * Gets the set of pages the user has requested (or generated)
206 * @return ApiPageSet
207 */
208 public function getPageSet() {
209 return $this->mPageSet;
210 }
211
212 /**
213 * Get the array mapping module names to class names
214 * @deprecated since 1.21, use getModuleManager()'s methods instead
215 * @return array array(modulename => classname)
216 */
217 public function getModules() {
218 wfDeprecated( __METHOD__, '1.21' );
219 return $this->getModuleManager()->getNamesWithClasses();
220 }
221
222 /**
223 * Get the generators array mapping module names to class names
224 * @return array array(modulename => classname)
225 */
226 public function getGenerators() {
227 return $this->mQueryGenerators;
228 }
229
230 /**
231 * Get whether the specified module is a prop, list or a meta query module
232 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
233 * @param $moduleName string Name of the module to find type for
234 * @return mixed string or null
235 */
236 function getModuleType( $moduleName ) {
237 return $this->getModuleManager()->getModuleGroup( $moduleName );
238 }
239
240 /**
241 * @return ApiFormatRaw|null
242 */
243 public function getCustomPrinter() {
244 // If &exportnowrap is set, use the raw formatter
245 if ( $this->getParameter( 'export' ) &&
246 $this->getParameter( 'exportnowrap' ) )
247 {
248 return new ApiFormatRaw( $this->getMain(),
249 $this->getMain()->createPrinterByName( 'xml' ) );
250 } else {
251 return null;
252 }
253 }
254
255 /**
256 * Query execution happens in the following steps:
257 * #1 Create a PageSet object with any pages requested by the user
258 * #2 If using a generator, execute it to get a new ApiPageSet object
259 * #3 Instantiate all requested modules.
260 * This way the PageSet object will know what shared data is required,
261 * and minimize DB calls.
262 * #4 Output all normalization and redirect resolution information
263 * #5 Execute all requested modules
264 */
265 public function execute() {
266 $this->params = $this->extractRequestParams();
267 $this->iwUrl = $this->params['iwurl'];
268
269 // Instantiate requested modules
270 $modules = array();
271 $this->instantiateModules( $modules, 'prop' );
272 $this->instantiateModules( $modules, 'list' );
273 $this->instantiateModules( $modules, 'meta' );
274
275 // Query modules may optimize data requests through the $this->getPageSet()
276 // object by adding extra fields from the page table.
277 // This function will gather all the extra request fields from the modules.
278 foreach ( $modules as $module ) {
279 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
280 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $module->getModuleName() ) );
281 }
282
283 $module->requestExtraData( $this->mPageSet );
284 }
285
286 // Populate page/revision information
287 $this->mPageSet->execute();
288 $cacheMode = $this->mPageSet->getCacheMode();
289
290 // Record page information (title, namespace, if exists, etc)
291 $this->outputGeneralPageInfo();
292
293 // Execute all requested modules.
294 /**
295 * @var $module ApiQueryBase
296 */
297 foreach ( $modules as $module ) {
298 $params = $module->extractRequestParams();
299 $cacheMode = $this->mergeCacheMode(
300 $cacheMode, $module->getCacheMode( $params ) );
301 $module->profileIn();
302 $module->execute();
303 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
304 $module->profileOut();
305 }
306
307 // Set the cache mode
308 $this->getMain()->setCacheMode( $cacheMode );
309 }
310
311 /**
312 * Update a cache mode string, applying the cache mode of a new module to it.
313 * The cache mode may increase in the level of privacy, but public modules
314 * added to private data do not decrease the level of privacy.
315 *
316 * @param $cacheMode string
317 * @param $modCacheMode string
318 * @return string
319 */
320 protected function mergeCacheMode( $cacheMode, $modCacheMode ) {
321 if ( $modCacheMode === 'anon-public-user-private' ) {
322 if ( $cacheMode !== 'private' ) {
323 $cacheMode = 'anon-public-user-private';
324 }
325 } elseif ( $modCacheMode === 'public' ) {
326 // do nothing, if it's public already it will stay public
327 } else { // private
328 $cacheMode = 'private';
329 }
330 return $cacheMode;
331 }
332
333 /**
334 * Create instances of all modules requested by the client
335 * @param $modules Array to append instantiated modules to
336 * @param $param string Parameter name to read modules from
337 */
338 private function instantiateModules( &$modules, $param ) {
339 if ( isset( $this->params[$param] ) ) {
340 foreach ( $this->params[$param] as $moduleName ) {
341 $modules[] = $this->mModuleMgr->getModule( $moduleName );
342 }
343 }
344 }
345
346 /**
347 * Appends an element for each page in the current pageSet with the
348 * most general information (id, title), plus any title normalizations
349 * and missing or invalid title/pageids/revids.
350 */
351 private function outputGeneralPageInfo() {
352 $pageSet = $this->getPageSet();
353 $result = $this->getResult();
354
355 // We don't check for a full result set here because we can't be adding
356 // more than 380K. The maximum revision size is in the megabyte range,
357 // and the maximum result size must be even higher than that.
358
359 $values = $pageSet->getNormalizedTitlesAsResult( $result );
360 if ( $values ) {
361 $result->addValue( 'query', 'normalized', $values );
362 }
363 $values = $pageSet->getConvertedTitlesAsResult( $result );
364 if ( $values ) {
365 $result->addValue( 'query', 'converted', $values );
366 }
367 $values = $pageSet->getInterwikiTitlesAsResult( $result, $this->iwUrl );
368 if ( $values ) {
369 $result->addValue( 'query', 'interwiki', $values );
370 }
371 $values = $pageSet->getRedirectTitlesAsResult( $result );
372 if ( $values ) {
373 $result->addValue( 'query', 'redirects', $values );
374 }
375 $values = $pageSet->getMissingRevisionIDsAsResult( $result );
376 if ( $values ) {
377 $result->addValue( 'query', 'badrevids', $values );
378 }
379
380 // Page elements
381 $pages = array();
382
383 // Report any missing titles
384 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
385 $vals = array();
386 ApiQueryBase::addTitleInfo( $vals, $title );
387 $vals['missing'] = '';
388 $pages[$fakeId] = $vals;
389 }
390 // Report any invalid titles
391 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
392 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
393 }
394 // Report any missing page ids
395 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
396 $pages[$pageid] = array(
397 'pageid' => $pageid,
398 'missing' => ''
399 );
400 }
401 // Report special pages
402 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
403 $vals = array();
404 ApiQueryBase::addTitleInfo( $vals, $title );
405 $vals['special'] = '';
406 if ( $title->isSpecialPage() &&
407 !SpecialPageFactory::exists( $title->getDbKey() ) ) {
408 $vals['missing'] = '';
409 } elseif ( $title->getNamespace() == NS_MEDIA &&
410 !wfFindFile( $title ) ) {
411 $vals['missing'] = '';
412 }
413 $pages[$fakeId] = $vals;
414 }
415
416 // Output general page information for found titles
417 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
418 $vals = array();
419 $vals['pageid'] = $pageid;
420 ApiQueryBase::addTitleInfo( $vals, $title );
421 $pages[$pageid] = $vals;
422 }
423
424 if ( count( $pages ) ) {
425 if ( $this->params['indexpageids'] ) {
426 $pageIDs = array_keys( $pages );
427 // json treats all map keys as strings - converting to match
428 $pageIDs = array_map( 'strval', $pageIDs );
429 $result->setIndexedTagName( $pageIDs, 'id' );
430 $result->addValue( 'query', 'pageids', $pageIDs );
431 }
432
433 $result->setIndexedTagName( $pages, 'page' );
434 $result->addValue( 'query', 'pages', $pages );
435 }
436 if ( $this->params['export'] ) {
437 $this->doExport( $pageSet, $result );
438 }
439 }
440
441 /**
442 * @param $pageSet ApiPageSet Pages to be exported
443 * @param $result ApiResult Result to output to
444 */
445 private function doExport( $pageSet, $result ) {
446 $exportTitles = array();
447 $titles = $pageSet->getGoodTitles();
448 if ( count( $titles ) ) {
449 $user = $this->getUser();
450 foreach ( $titles as $title ) {
451 if ( $title->userCan( 'read', $user ) ) {
452 $exportTitles[] = $title;
453 }
454 }
455 }
456
457 $exporter = new WikiExporter( $this->getDB() );
458 // WikiExporter writes to stdout, so catch its
459 // output with an ob
460 ob_start();
461 $exporter->openStream();
462 foreach ( $exportTitles as $title ) {
463 $exporter->pageByTitle( $title );
464 }
465 $exporter->closeStream();
466 $exportxml = ob_get_contents();
467 ob_end_clean();
468
469 // Don't check the size of exported stuff
470 // It's not continuable, so it would cause more
471 // problems than it'd solve
472 $result->disableSizeCheck();
473 if ( $this->params['exportnowrap'] ) {
474 $result->reset();
475 // Raw formatter will handle this
476 $result->addValue( null, 'text', $exportxml );
477 $result->addValue( null, 'mime', 'text/xml' );
478 } else {
479 $r = array();
480 ApiResult::setContent( $r, $exportxml );
481 $result->addValue( 'query', 'export', $r );
482 }
483 $result->enableSizeCheck();
484 }
485
486 public function getAllowedParams( $flags = 0 ) {
487 $result = array(
488 'prop' => array(
489 ApiBase::PARAM_ISMULTI => true,
490 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'prop' )
491 ),
492 'list' => array(
493 ApiBase::PARAM_ISMULTI => true,
494 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'list' )
495 ),
496 'meta' => array(
497 ApiBase::PARAM_ISMULTI => true,
498 ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'meta' )
499 ),
500 'indexpageids' => false,
501 'export' => false,
502 'exportnowrap' => false,
503 'iwurl' => false,
504 );
505 if( $flags ) {
506 $result += $this->getPageSet()->getFinalParams( $flags );
507 }
508 return $result;
509 }
510
511 /**
512 * Override the parent to generate help messages for all available query modules.
513 * @return string
514 */
515 public function makeHelpMsg() {
516
517 // Use parent to make default message for the query module
518 $msg = parent::makeHelpMsg();
519
520 $querySeparator = str_repeat( '--- ', 12 );
521 $moduleSeparator = str_repeat( '*** ', 14 );
522 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
523 $msg .= $this->makeHelpMsgHelper( 'prop' );
524 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
525 $msg .= $this->makeHelpMsgHelper( 'list' );
526 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
527 $msg .= $this->makeHelpMsgHelper( 'meta' );
528 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
529
530 return $msg;
531 }
532
533 /**
534 * For all modules of a given group, generate help messages and join them together
535 * @param $group string Module group
536 * @return string
537 */
538 private function makeHelpMsgHelper( $group ) {
539 $moduleDescriptions = array();
540
541 $moduleNames = $this->mModuleMgr->getNames( $group );
542 sort( $moduleNames );
543 foreach ( $moduleNames as $name ) {
544 /**
545 * @var $module ApiQueryBase
546 */
547 $module = $this->mModuleMgr->getModule( $name );
548
549 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
550 $msg2 = $module->makeHelpMsg();
551 if ( $msg2 !== false ) {
552 $msg .= $msg2;
553 }
554 if ( $module instanceof ApiQueryGeneratorBase ) {
555 $msg .= "Generator:\n This module may be used as a generator\n";
556 }
557 $moduleDescriptions[] = $msg;
558 }
559
560 return implode( "\n", $moduleDescriptions );
561 }
562
563 public function shouldCheckMaxlag() {
564 return true;
565 }
566
567 public function getParamDescription() {
568 return $this->getPageSet()->getParamDescription() + array(
569 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
570 'list' => 'Which lists to get. Module help is available below',
571 'meta' => 'Which metadata to get about the site. Module help is available below',
572 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
573 'export' => 'Export the current revisions of all given or generated pages',
574 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
575 'iwurl' => 'Whether to get the full URL if the title is an interwiki link',
576 );
577 }
578
579 public function getDescription() {
580 return array(
581 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
582 'and is loosely based on the old query.php interface.',
583 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites'
584 );
585 }
586
587 public function getPossibleErrors() {
588 return array_merge(
589 parent::getPossibleErrors(),
590 $this->getPageSet()->getPossibleErrors()
591 );
592 }
593
594 public function getExamples() {
595 return array(
596 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
597 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
598 );
599 }
600
601 public function getHelpUrls() {
602 return array(
603 'https://www.mediawiki.org/wiki/API:Meta',
604 'https://www.mediawiki.org/wiki/API:Properties',
605 'https://www.mediawiki.org/wiki/API:Lists',
606 );
607 }
608 }