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