Merge "convertExtensionToRegistration: Detect if composer autoloader is needed"
[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 generators array mapping module names to class names
189 * @deprecated since 1.21, list of generators is maintained by ApiPageSet
190 * @return array Array(modulename => classname)
191 */
192 public function getGenerators() {
193 wfDeprecated( __METHOD__, '1.21' );
194 $gens = array();
195 foreach ( $this->mModuleMgr->getNamesWithClasses() as $name => $class ) {
196 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
197 $gens[$name] = $class;
198 }
199 }
200
201 return $gens;
202 }
203
204 /**
205 * Get whether the specified module is a prop, list or a meta query module
206 * @deprecated since 1.21, use getModuleManager()->getModuleGroup()
207 * @param string $moduleName Name of the module to find type for
208 * @return string|null
209 */
210 function getModuleType( $moduleName ) {
211 return $this->getModuleManager()->getModuleGroup( $moduleName );
212 }
213
214 /**
215 * @return ApiFormatRaw|null
216 */
217 public function getCustomPrinter() {
218 // If &exportnowrap is set, use the raw formatter
219 if ( $this->getParameter( 'export' ) &&
220 $this->getParameter( 'exportnowrap' )
221 ) {
222 return new ApiFormatRaw( $this->getMain(),
223 $this->getMain()->createPrinterByName( 'xml' ) );
224 } else {
225 return null;
226 }
227 }
228
229 /**
230 * Query execution happens in the following steps:
231 * #1 Create a PageSet object with any pages requested by the user
232 * #2 If using a generator, execute it to get a new ApiPageSet object
233 * #3 Instantiate all requested modules.
234 * This way the PageSet object will know what shared data is required,
235 * and minimize DB calls.
236 * #4 Output all normalization and redirect resolution information
237 * #5 Execute all requested modules
238 */
239 public function execute() {
240 $this->mParams = $this->extractRequestParams();
241
242 // Instantiate requested modules
243 $allModules = array();
244 $this->instantiateModules( $allModules, 'prop' );
245 $propModules = array_keys( $allModules );
246 $this->instantiateModules( $allModules, 'list' );
247 $this->instantiateModules( $allModules, 'meta' );
248
249 // Filter modules based on continue parameter
250 $continuationManager = new ApiContinuationManager( $this, $allModules, $propModules );
251 $this->setContinuationManager( $continuationManager );
252 $modules = $continuationManager->getRunModules();
253
254 if ( !$continuationManager->isGeneratorDone() ) {
255 // Query modules may optimize data requests through the $this->getPageSet()
256 // object by adding extra fields from the page table.
257 foreach ( $modules as $module ) {
258 $module->requestExtraData( $this->mPageSet );
259 }
260 // Populate page/revision information
261 $this->mPageSet->execute();
262 // Record page information (title, namespace, if exists, etc)
263 $this->outputGeneralPageInfo();
264 } else {
265 $this->mPageSet->executeDryRun();
266 }
267
268 $cacheMode = $this->mPageSet->getCacheMode();
269
270 // Execute all unfinished modules
271 /** @var $module ApiQueryBase */
272 foreach ( $modules as $module ) {
273 $params = $module->extractRequestParams();
274 $cacheMode = $this->mergeCacheMode(
275 $cacheMode, $module->getCacheMode( $params ) );
276 $module->execute();
277 Hooks::run( 'APIQueryAfterExecute', array( &$module ) );
278 }
279
280 // Set the cache mode
281 $this->getMain()->setCacheMode( $cacheMode );
282
283 // Write the continuation data into the result
284 $this->setContinuationManager( null );
285 if ( $this->mParams['rawcontinue'] ) {
286 $data = $continuationManager->getRawContinuation();
287 if ( $data ) {
288 $this->getResult()->addValue( null, 'query-continue', $data,
289 ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
290 }
291 } else {
292 $continuationManager->setContinuationIntoResult( $this->getResult() );
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'] = true;
385 $pages[$fakeId] = $vals;
386 }
387 // Report any invalid titles
388 foreach ( $pageSet->getInvalidTitlesAndReasons() as $fakeId => $data ) {
389 $pages[$fakeId] = $data + array( 'invalid' => true );
390 }
391 // Report any missing page ids
392 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
393 $pages[$pageid] = array(
394 'pageid' => $pageid,
395 'missing' => true
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'] = true;
404 if ( $title->isSpecialPage() &&
405 !SpecialPageFactory::exists( $title->getDBkey() )
406 ) {
407 $vals['missing'] = true;
408 } elseif ( $title->getNamespace() == NS_MEDIA &&
409 !wfFindFile( $title )
410 ) {
411 $vals['missing'] = true;
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 $pageSet->populateGeneratorData( $pages );
426 ApiResult::setArrayType( $pages, 'BCarray' );
427
428 if ( $this->mParams['indexpageids'] ) {
429 $pageIDs = array_keys( ApiResult::stripMetadataNonRecursive( $pages ) );
430 // json treats all map keys as strings - converting to match
431 $pageIDs = array_map( 'strval', $pageIDs );
432 ApiResult::setIndexedTagName( $pageIDs, 'id' );
433 $fit = $fit && $result->addValue( 'query', 'pageids', $pageIDs );
434 }
435
436 ApiResult::setIndexedTagName( $pages, 'page' );
437 $fit = $fit && $result->addValue( 'query', 'pages', $pages );
438 }
439
440 if ( !$fit ) {
441 $this->dieUsage(
442 'The value of $wgAPIMaxResultSize on this wiki is ' .
443 'too small to hold basic result information',
444 'badconfig'
445 );
446 }
447
448 if ( $this->mParams['export'] ) {
449 $this->doExport( $pageSet, $result );
450 }
451 }
452
453 /**
454 * This method is called by the generator base when generator in the smart-continue
455 * mode tries to set 'query-continue' value. ApiQuery stores those values separately
456 * until the post-processing when it is known if the generation should continue or repeat.
457 * @deprecated since 1.24
458 * @param ApiQueryGeneratorBase $module Generator module
459 * @param string $paramName
460 * @param mixed $paramValue
461 * @return bool True if processed, false if this is a legacy continue
462 */
463 public function setGeneratorContinue( $module, $paramName, $paramValue ) {
464 wfDeprecated( __METHOD__, '1.24' );
465 $this->getContinuationManager()->addGeneratorContinueParam( $module, $paramName, $paramValue );
466 return !$this->getParameter( 'rawcontinue' );
467 }
468
469 /**
470 * @param ApiPageSet $pageSet Pages to be exported
471 * @param ApiResult $result Result to output to
472 */
473 private function doExport( $pageSet, $result ) {
474 $exportTitles = array();
475 $titles = $pageSet->getGoodTitles();
476 if ( count( $titles ) ) {
477 $user = $this->getUser();
478 /** @var $title Title */
479 foreach ( $titles as $title ) {
480 if ( $title->userCan( 'read', $user ) ) {
481 $exportTitles[] = $title;
482 }
483 }
484 }
485
486 $exporter = new WikiExporter( $this->getDB() );
487 // WikiExporter writes to stdout, so catch its
488 // output with an ob
489 ob_start();
490 $exporter->openStream();
491 foreach ( $exportTitles as $title ) {
492 $exporter->pageByTitle( $title );
493 }
494 $exporter->closeStream();
495 $exportxml = ob_get_contents();
496 ob_end_clean();
497
498 // Don't check the size of exported stuff
499 // It's not continuable, so it would cause more
500 // problems than it'd solve
501 if ( $this->mParams['exportnowrap'] ) {
502 $result->reset();
503 // Raw formatter will handle this
504 $result->addValue( null, 'text', $exportxml, ApiResult::NO_SIZE_CHECK );
505 $result->addValue( null, 'mime', 'text/xml', ApiResult::NO_SIZE_CHECK );
506 } else {
507 $result->addValue( 'query', 'export', $exportxml, ApiResult::NO_SIZE_CHECK );
508 $result->addValue( 'query', ApiResult::META_BC_SUBELEMENTS, array( 'export' ) );
509 }
510 }
511
512 public function getAllowedParams( $flags = 0 ) {
513 $result = array(
514 'prop' => array(
515 ApiBase::PARAM_ISMULTI => true,
516 ApiBase::PARAM_TYPE => 'submodule',
517 ),
518 'list' => array(
519 ApiBase::PARAM_ISMULTI => true,
520 ApiBase::PARAM_TYPE => 'submodule',
521 ),
522 'meta' => array(
523 ApiBase::PARAM_ISMULTI => true,
524 ApiBase::PARAM_TYPE => 'submodule',
525 ),
526 'indexpageids' => false,
527 'export' => false,
528 'exportnowrap' => false,
529 'iwurl' => false,
530 'continue' => array(
531 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
532 ),
533 'rawcontinue' => false,
534 );
535 if ( $flags ) {
536 $result += $this->getPageSet()->getFinalParams( $flags );
537 }
538
539 return $result;
540 }
541
542 /**
543 * Override the parent to generate help messages for all available query modules.
544 * @deprecated since 1.25
545 * @return string
546 */
547 public function makeHelpMsg() {
548 wfDeprecated( __METHOD__, '1.25' );
549
550 // Use parent to make default message for the query module
551 $msg = parent::makeHelpMsg();
552
553 $querySeparator = str_repeat( '--- ', 12 );
554 $moduleSeparator = str_repeat( '*** ', 14 );
555 $msg .= "\n$querySeparator Query: Prop $querySeparator\n\n";
556 $msg .= $this->makeHelpMsgHelper( 'prop' );
557 $msg .= "\n$querySeparator Query: List $querySeparator\n\n";
558 $msg .= $this->makeHelpMsgHelper( 'list' );
559 $msg .= "\n$querySeparator Query: Meta $querySeparator\n\n";
560 $msg .= $this->makeHelpMsgHelper( 'meta' );
561 $msg .= "\n\n$moduleSeparator Modules: continuation $moduleSeparator\n\n";
562
563 return $msg;
564 }
565
566 /**
567 * For all modules of a given group, generate help messages and join them together
568 * @deprecated since 1.25
569 * @param string $group Module group
570 * @return string
571 */
572 private function makeHelpMsgHelper( $group ) {
573 $moduleDescriptions = array();
574
575 $moduleNames = $this->mModuleMgr->getNames( $group );
576 sort( $moduleNames );
577 foreach ( $moduleNames as $name ) {
578 /**
579 * @var $module ApiQueryBase
580 */
581 $module = $this->mModuleMgr->getModule( $name );
582
583 $msg = ApiMain::makeHelpMsgHeader( $module, $group );
584 $msg2 = $module->makeHelpMsg();
585 if ( $msg2 !== false ) {
586 $msg .= $msg2;
587 }
588 if ( $module instanceof ApiQueryGeneratorBase ) {
589 $msg .= "Generator:\n This module may be used as a generator\n";
590 }
591 $moduleDescriptions[] = $msg;
592 }
593
594 return implode( "\n", $moduleDescriptions );
595 }
596
597 protected function getExamplesMessages() {
598 return array(
599 'action=query&prop=revisions&meta=siteinfo&' .
600 'titles=Main%20Page&rvprop=user|comment&continue='
601 => 'apihelp-query-example-revisions',
602 'action=query&generator=allpages&gapprefix=API/&prop=revisions&continue='
603 => 'apihelp-query-example-allpages',
604 );
605 }
606
607 public function getHelpUrls() {
608 return array(
609 'https://www.mediawiki.org/wiki/API:Query',
610 'https://www.mediawiki.org/wiki/API:Meta',
611 'https://www.mediawiki.org/wiki/API:Properties',
612 'https://www.mediawiki.org/wiki/API:Lists',
613 );
614 }
615 }