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