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