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