Follow-up r69233: Add existence check for NS_MEDIA titles
[lhc/web/wiklou.git] / includes / api / ApiQuery.php
1 <?php
2
3 /**
4 * Created on Sep 7, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
29 }
30
31 /**
32 * This is the main query class. It behaves similar to ApiMain: based on the
33 * parameters given, it will create a list of titles to work on (an ApiPageSet
34 * object), instantiate and execute various property/list/meta modules, and
35 * assemble all resulting data into a single ApiResult object.
36 *
37 * In generator mode, a generator will be executed first to populate a second
38 * ApiPageSet object, and that object will be used for all subsequent modules.
39 *
40 * @ingroup API
41 */
42 class ApiQuery extends ApiBase {
43
44 private $mPropModuleNames, $mListModuleNames, $mMetaModuleNames;
45 private $mPageSet;
46 private $params, $redirect;
47
48 private $mQueryPropModules = array(
49 'info' => 'ApiQueryInfo',
50 'revisions' => 'ApiQueryRevisions',
51 'links' => 'ApiQueryLinks',
52 'iwlinks' => 'ApiQueryIWLinks',
53 'langlinks' => 'ApiQueryLangLinks',
54 'images' => 'ApiQueryImages',
55 'imageinfo' => 'ApiQueryImageInfo',
56 'templates' => 'ApiQueryLinks',
57 'categories' => 'ApiQueryCategories',
58 'extlinks' => 'ApiQueryExternalLinks',
59 'categoryinfo' => 'ApiQueryCategoryInfo',
60 'duplicatefiles' => 'ApiQueryDuplicateFiles',
61 );
62
63 private $mQueryListModules = array(
64 'allimages' => 'ApiQueryAllimages',
65 'allpages' => 'ApiQueryAllpages',
66 'alllinks' => 'ApiQueryAllLinks',
67 'allcategories' => 'ApiQueryAllCategories',
68 'allusers' => 'ApiQueryAllUsers',
69 'backlinks' => 'ApiQueryBacklinks',
70 'blocks' => 'ApiQueryBlocks',
71 'categorymembers' => 'ApiQueryCategoryMembers',
72 'deletedrevs' => 'ApiQueryDeletedrevs',
73 'embeddedin' => 'ApiQueryBacklinks',
74 'filearchive' => 'ApiQueryFilearchive',
75 'imageusage' => 'ApiQueryBacklinks',
76 'iwbacklinks' => 'ApiQueryIWBacklinks',
77 'logevents' => 'ApiQueryLogEvents',
78 'recentchanges' => 'ApiQueryRecentChanges',
79 'search' => 'ApiQuerySearch',
80 'tags' => 'ApiQueryTags',
81 'usercontribs' => 'ApiQueryContributions',
82 'watchlist' => 'ApiQueryWatchlist',
83 'watchlistraw' => 'ApiQueryWatchlistRaw',
84 'exturlusage' => 'ApiQueryExtLinksUsage',
85 'users' => 'ApiQueryUsers',
86 'random' => 'ApiQueryRandom',
87 'protectedtitles' => 'ApiQueryProtectedTitles',
88 );
89
90 private $mQueryMetaModules = array(
91 'siteinfo' => 'ApiQuerySiteinfo',
92 'userinfo' => 'ApiQueryUserInfo',
93 'allmessages' => 'ApiQueryAllmessages',
94 );
95
96 private $mSlaveDB = null;
97 private $mNamedDB = array();
98
99 public function __construct( $main, $action ) {
100 parent::__construct( $main, $action );
101
102 // Allow custom modules to be added in LocalSettings.php
103 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
104 self::appendUserModules( $this->mQueryPropModules, $wgAPIPropModules );
105 self::appendUserModules( $this->mQueryListModules, $wgAPIListModules );
106 self::appendUserModules( $this->mQueryMetaModules, $wgAPIMetaModules );
107
108 $this->mPropModuleNames = array_keys( $this->mQueryPropModules );
109 $this->mListModuleNames = array_keys( $this->mQueryListModules );
110 $this->mMetaModuleNames = array_keys( $this->mQueryMetaModules );
111
112 // Allow the entire list of modules at first,
113 // but during module instantiation check if it can be used as a generator.
114 $this->mAllowedGenerators = array_merge( $this->mListModuleNames, $this->mPropModuleNames );
115 }
116
117 /**
118 * Helper function to append any add-in modules to the list
119 * @param $modules array Module array
120 * @param $newModules array Module array to add to $modules
121 */
122 private static function appendUserModules( &$modules, $newModules ) {
123 if ( is_array( $newModules ) ) {
124 foreach ( $newModules as $moduleName => $moduleClass ) {
125 $modules[$moduleName] = $moduleClass;
126 }
127 }
128 }
129
130 /**
131 * Gets a default slave database connection object
132 * @return Database
133 */
134 public function getDB() {
135 if ( !isset( $this->mSlaveDB ) ) {
136 $this->profileDBIn();
137 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
138 $this->profileDBOut();
139 }
140 return $this->mSlaveDB;
141 }
142
143 /**
144 * Get the query database connection with the given name.
145 * If no such connection has been requested before, it will be created.
146 * Subsequent calls with the same $name will return the same connection
147 * as the first, regardless of the values of $db and $groups
148 * @param $name string Name to assign to the database connection
149 * @param $db int One of the DB_* constants
150 * @param $groups array Query groups
151 * @return Database
152 */
153 public function getNamedDB( $name, $db, $groups ) {
154 if ( !array_key_exists( $name, $this->mNamedDB ) ) {
155 $this->profileDBIn();
156 $this->mNamedDB[$name] = wfGetDB( $db, $groups );
157 $this->profileDBOut();
158 }
159 return $this->mNamedDB[$name];
160 }
161
162 /**
163 * Gets the set of pages the user has requested (or generated)
164 * @return ApiPageSet
165 */
166 public function getPageSet() {
167 return $this->mPageSet;
168 }
169
170 /**
171 * Get the array mapping module names to class names
172 * @return array(modulename => classname)
173 */
174 function getModules() {
175 return array_merge( $this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules );
176 }
177
178 /**
179 * Get whether the specified module is a prop, list or a meta query module
180 * @param $moduleName string Name of the module to find type for
181 * @return mixed string or null
182 */
183 function getModuleType( $moduleName ) {
184 if ( array_key_exists ( $moduleName, $this->mQueryPropModules ) ) {
185 return 'prop';
186 }
187
188 if ( array_key_exists ( $moduleName, $this->mQueryListModules ) ) {
189 return 'list';
190 }
191
192 if ( array_key_exists ( $moduleName, $this->mQueryMetaModules ) ) {
193 return 'meta';
194 }
195
196 return null;
197 }
198
199 public function getCustomPrinter() {
200 // If &exportnowrap is set, use the raw formatter
201 if ( $this->getParameter( 'export' ) &&
202 $this->getParameter( 'exportnowrap' ) )
203 {
204 return new ApiFormatRaw( $this->getMain(),
205 $this->getMain()->createPrinterByName( 'xml' ) );
206 } else {
207 return null;
208 }
209 }
210
211 /**
212 * Query execution happens in the following steps:
213 * #1 Create a PageSet object with any pages requested by the user
214 * #2 If using a generator, execute it to get a new ApiPageSet object
215 * #3 Instantiate all requested modules.
216 * This way the PageSet object will know what shared data is required,
217 * and minimize DB calls.
218 * #4 Output all normalization and redirect resolution information
219 * #5 Execute all requested modules
220 */
221 public function execute() {
222 $this->params = $this->extractRequestParams();
223 $this->redirects = $this->params['redirects'];
224 $this->convertTitles = $this->params['converttitles'];
225
226 // Create PageSet
227 $this->mPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
228
229 // Instantiate requested modules
230 $modules = array();
231 $this->instantiateModules( $modules, 'prop', $this->mQueryPropModules );
232 $this->instantiateModules( $modules, 'list', $this->mQueryListModules );
233 $this->instantiateModules( $modules, 'meta', $this->mQueryMetaModules );
234
235 // If given, execute generator to substitute user supplied data with generated data.
236 if ( isset( $this->params['generator'] ) ) {
237 $this->executeGeneratorModule( $this->params['generator'], $modules );
238 } else {
239 // Append custom fields and populate page/revision information
240 $this->addCustomFldsToPageSet( $modules, $this->mPageSet );
241 $this->mPageSet->execute();
242 }
243
244 // Record page information (title, namespace, if exists, etc)
245 $this->outputGeneralPageInfo();
246
247 // Execute all requested modules.
248 foreach ( $modules as $module ) {
249 $module->profileIn();
250 $module->execute();
251 wfRunHooks( 'APIQueryAfterExecute', array( &$module ) );
252 $module->profileOut();
253 }
254 }
255
256 /**
257 * Query modules may optimize data requests through the $this->getPageSet() object
258 * by adding extra fields from the page table.
259 * This function will gather all the extra request fields from the modules.
260 * @param $modules array of module objects
261 * @param $pageSet ApiPageSet
262 */
263 private function addCustomFldsToPageSet( $modules, $pageSet ) {
264 // Query all requested modules.
265 foreach ( $modules as $module ) {
266 $module->requestExtraData( $pageSet );
267 }
268 }
269
270 /**
271 * Create instances of all modules requested by the client
272 * @param $modules array to append instatiated modules to
273 * @param $param string Parameter name to read modules from
274 * @param $moduleList array(modulename => classname)
275 */
276 private function instantiateModules( &$modules, $param, $moduleList ) {
277 $list = @$this->params[$param];
278 if ( !is_null ( $list ) ) {
279 foreach ( $list as $moduleName ) {
280 $modules[] = new $moduleList[$moduleName] ( $this, $moduleName );
281 }
282 }
283 }
284
285 /**
286 * Appends an element for each page in the current pageSet with the
287 * most general information (id, title), plus any title normalizations
288 * and missing or invalid title/pageids/revids.
289 */
290 private function outputGeneralPageInfo() {
291 $pageSet = $this->getPageSet();
292 $result = $this->getResult();
293
294 // We don't check for a full result set here because we can't be adding
295 // more than 380K. The maximum revision size is in the megabyte range,
296 // and the maximum result size must be even higher than that.
297
298 // Title normalizations
299 $normValues = array();
300 foreach ( $pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
301 $normValues[] = array(
302 'from' => $rawTitleStr,
303 'to' => $titleStr
304 );
305 }
306
307 if ( count( $normValues ) ) {
308 $result->setIndexedTagName( $normValues, 'n' );
309 $result->addValue( 'query', 'normalized', $normValues );
310 }
311
312 // Title conversions
313 $convValues = array();
314 foreach ( $pageSet->getConvertedTitles() as $rawTitleStr => $titleStr ) {
315 $convValues[] = array(
316 'from' => $rawTitleStr,
317 'to' => $titleStr
318 );
319 }
320
321 if ( count( $convValues ) ) {
322 $result->setIndexedTagName( $convValues, 'c' );
323 $result->addValue( 'query', 'converted', $convValues );
324 }
325
326 // Interwiki titles
327 $intrwValues = array();
328 foreach ( $pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
329 $intrwValues[] = array(
330 'title' => $rawTitleStr,
331 'iw' => $interwikiStr
332 );
333 }
334
335 if ( count( $intrwValues ) ) {
336 $result->setIndexedTagName( $intrwValues, 'i' );
337 $result->addValue( 'query', 'interwiki', $intrwValues );
338 }
339
340 // Show redirect information
341 $redirValues = array();
342 foreach ( $pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo ) {
343 $redirValues[] = array(
344 'from' => strval( $titleStrFrom ),
345 'to' => $titleStrTo
346 );
347 }
348
349 if ( count( $redirValues ) ) {
350 $result->setIndexedTagName( $redirValues, 'r' );
351 $result->addValue( 'query', 'redirects', $redirValues );
352 }
353
354 //
355 // Missing revision elements
356 //
357 $missingRevIDs = $pageSet->getMissingRevisionIDs();
358 if ( count( $missingRevIDs ) ) {
359 $revids = array();
360 foreach ( $missingRevIDs as $revid ) {
361 $revids[$revid] = array(
362 'revid' => $revid
363 );
364 }
365 $result->setIndexedTagName( $revids, 'rev' );
366 $result->addValue( 'query', 'badrevids', $revids );
367 }
368
369 //
370 // Page elements
371 //
372 $pages = array();
373
374 // Report any missing titles
375 foreach ( $pageSet->getMissingTitles() as $fakeId => $title ) {
376 $vals = array();
377 ApiQueryBase::addTitleInfo( $vals, $title );
378 $vals['missing'] = '';
379 $pages[$fakeId] = $vals;
380 }
381 // Report any invalid titles
382 foreach ( $pageSet->getInvalidTitles() as $fakeId => $title ) {
383 $pages[$fakeId] = array( 'title' => $title, 'invalid' => '' );
384 }
385 // Report any missing page ids
386 foreach ( $pageSet->getMissingPageIDs() as $pageid ) {
387 $pages[$pageid] = array(
388 'pageid' => $pageid,
389 'missing' => ''
390 );
391 }
392 // Report special pages
393 foreach ( $pageSet->getSpecialTitles() as $fakeId => $title ) {
394 $vals = array();
395 ApiQueryBase::addTitleInfo( $vals, $title );
396 $vals['special'] = '';
397 if ( $title->getNamespace() == NS_SPECIAL &&
398 !SpecialPage::exists( $title->getText() ) ) {
399 $vals['missing'] = '';
400 } elseif ( $title->getNamespace() == NS_MEDIA &&
401 !wfFindFile( $title ) ) {
402 $vals['missing'] = '';
403 }
404 $pages[$fakeId] = $vals;
405 }
406
407 // Output general page information for found titles
408 foreach ( $pageSet->getGoodTitles() as $pageid => $title ) {
409 $vals = array();
410 $vals['pageid'] = $pageid;
411 ApiQueryBase::addTitleInfo( $vals, $title );
412 $pages[$pageid] = $vals;
413 }
414
415 if ( count( $pages ) ) {
416 if ( $this->params['indexpageids'] ) {
417 $pageIDs = array_keys( $pages );
418 // json treats all map keys as strings - converting to match
419 $pageIDs = array_map( 'strval', $pageIDs );
420 $result->setIndexedTagName( $pageIDs, 'id' );
421 $result->addValue( 'query', 'pageids', $pageIDs );
422 }
423
424 $result->setIndexedTagName( $pages, 'page' );
425 $result->addValue( 'query', 'pages', $pages );
426 }
427 if ( $this->params['export'] ) {
428 $exporter = new WikiExporter( $this->getDB() );
429 // WikiExporter writes to stdout, so catch its
430 // output with an ob
431 ob_start();
432 $exporter->openStream();
433 foreach ( @$pageSet->getGoodTitles() as $title ) {
434 if ( $title->userCanRead() ) {
435 $exporter->pageByTitle( $title );
436 }
437 }
438 $exporter->closeStream();
439 $exportxml = ob_get_contents();
440 ob_end_clean();
441
442 // Don't check the size of exported stuff
443 // It's not continuable, so it would cause more
444 // problems than it'd solve
445 $result->disableSizeCheck();
446 if ( $this->params['exportnowrap'] ) {
447 $result->reset();
448 // Raw formatter will handle this
449 $result->addValue( null, 'text', $exportxml );
450 $result->addValue( null, 'mime', 'text/xml' );
451 } else {
452 $r = array();
453 ApiResult::setContent( $r, $exportxml );
454 $result->addValue( 'query', 'export', $r );
455 }
456 $result->enableSizeCheck();
457 }
458 }
459
460 /**
461 * For generator mode, execute generator, and use its output as new
462 * ApiPageSet
463 * @param $generatorName string Module name
464 * @param $modules array of module objects
465 */
466 protected function executeGeneratorModule( $generatorName, $modules ) {
467 // Find class that implements requested generator
468 if ( isset( $this->mQueryListModules[$generatorName] ) ) {
469 $className = $this->mQueryListModules[$generatorName];
470 } elseif ( isset( $this->mQueryPropModules[$generatorName] ) ) {
471 $className = $this->mQueryPropModules[$generatorName];
472 } else {
473 ApiBase::dieDebug( __METHOD__, "Unknown generator=$generatorName" );
474 }
475
476 // Generator results
477 $resultPageSet = new ApiPageSet( $this, $this->redirects, $this->convertTitles );
478
479 // Create and execute the generator
480 $generator = new $className ( $this, $generatorName );
481 if ( !$generator instanceof ApiQueryGeneratorBase ) {
482 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
483 }
484
485 $generator->setGeneratorMode();
486
487 // Add any additional fields modules may need
488 $generator->requestExtraData( $this->mPageSet );
489 $this->addCustomFldsToPageSet( $modules, $resultPageSet );
490
491 // Populate page information with the original user input
492 $this->mPageSet->execute();
493
494 // populate resultPageSet with the generator output
495 $generator->profileIn();
496 $generator->executeGenerator( $resultPageSet );
497 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$resultPageSet ) );
498 $resultPageSet->finishPageSetGeneration();
499 $generator->profileOut();
500
501 // Swap the resulting pageset back in
502 $this->mPageSet = $resultPageSet;
503 }
504
505 public function getAllowedParams() {
506 return array(
507 'prop' => array(
508 ApiBase::PARAM_ISMULTI => true,
509 ApiBase::PARAM_TYPE => $this->mPropModuleNames
510 ),
511 'list' => array(
512 ApiBase::PARAM_ISMULTI => true,
513 ApiBase::PARAM_TYPE => $this->mListModuleNames
514 ),
515 'meta' => array(
516 ApiBase::PARAM_ISMULTI => true,
517 ApiBase::PARAM_TYPE => $this->mMetaModuleNames
518 ),
519 'generator' => array(
520 ApiBase::PARAM_TYPE => $this->mAllowedGenerators
521 ),
522 'redirects' => false,
523 'converttitles' => false,
524 'indexpageids' => false,
525 'export' => false,
526 'exportnowrap' => false,
527 );
528 }
529
530 /**
531 * Override the parent to generate help messages for all available query modules.
532 * @return string
533 */
534 public function makeHelpMsg() {
535 $msg = '';
536
537 // Make sure the internal object is empty
538 // (just in case a sub-module decides to optimize during instantiation)
539 $this->mPageSet = null;
540 $this->mAllowedGenerators = array(); // Will be repopulated
541
542 $astriks = str_repeat( '--- ', 8 );
543 $astriks2 = str_repeat( '*** ', 10 );
544 $msg .= "\n$astriks Query: Prop $astriks\n\n";
545 $msg .= $this->makeHelpMsgHelper( $this->mQueryPropModules, 'prop' );
546 $msg .= "\n$astriks Query: List $astriks\n\n";
547 $msg .= $this->makeHelpMsgHelper( $this->mQueryListModules, 'list' );
548 $msg .= "\n$astriks Query: Meta $astriks\n\n";
549 $msg .= $this->makeHelpMsgHelper( $this->mQueryMetaModules, 'meta' );
550 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
551
552 // Perform the base call last because the $this->mAllowedGenerators
553 // will be updated inside makeHelpMsgHelper()
554 // Use parent to make default message for the query module
555 $msg = parent::makeHelpMsg() . $msg;
556
557 return $msg;
558 }
559
560 /**
561 * For all modules in $moduleList, generate help messages and join them together
562 * @param $moduleList array(modulename => classname)
563 * @param $paramName string Parameter name
564 * @return string
565 */
566 private function makeHelpMsgHelper( $moduleList, $paramName ) {
567 $moduleDescriptions = array();
568
569 foreach ( $moduleList as $moduleName => $moduleClass ) {
570 $module = new $moduleClass ( $this, $moduleName, null );
571
572 $msg = ApiMain::makeHelpMsgHeader( $module, $paramName );
573 $msg2 = $module->makeHelpMsg();
574 if ( $msg2 !== false ) {
575 $msg .= $msg2;
576 }
577 if ( $module instanceof ApiQueryGeneratorBase ) {
578 $this->mAllowedGenerators[] = $moduleName;
579 $msg .= "Generator:\n This module may be used as a generator\n";
580 }
581 $moduleDescriptions[] = $msg;
582 }
583
584 return implode( "\n", $moduleDescriptions );
585 }
586
587 /**
588 * Override to add extra parameters from PageSet
589 * @return string
590 */
591 public function makeHelpMsgParameters() {
592 $psModule = new ApiPageSet( $this );
593 return $psModule->makeHelpMsgParameters() . parent::makeHelpMsgParameters();
594 }
595
596 public function shouldCheckMaxlag() {
597 return true;
598 }
599
600 public function getParamDescription() {
601 return array(
602 'prop' => 'Which properties to get for the titles/revisions/pageids. Module help is available below',
603 'list' => 'Which lists to get. Module help is available below',
604 'meta' => 'Which metadata to get about the site. Module help is available below',
605 'generator' => array( 'Use the output of a list as the input for other prop/list/meta items',
606 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
607 'redirects' => 'Automatically resolve redirects',
608 'converttitles' => "Convert titles to other variants if necessary. Only works if the wiki's content language supports variant conversion.",
609 'indexpageids' => 'Include an additional pageids section listing all returned page IDs',
610 'export' => 'Export the current revisions of all given or generated pages',
611 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
612 );
613 }
614
615 public function getDescription() {
616 return array(
617 'Query API module allows applications to get needed pieces of data 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 token to prevent abuse from malicious sites'
620 );
621 }
622
623 public function getPossibleErrors() {
624 return array_merge( parent::getPossibleErrors(), array(
625 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
626 ) );
627 }
628
629 protected function getExamples() {
630 return array(
631 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
632 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
633 );
634 }
635
636 public function getVersion() {
637 $psModule = new ApiPageSet( $this );
638 $vers = array();
639 $vers[] = __CLASS__ . ': $Id$';
640 $vers[] = $psModule->getVersion();
641 return $vers;
642 }
643 }