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