]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiQuery.php
MediaWiki 1.14.0
[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 parameters given,
33  * it will create a list of titles to work on (an instance of the ApiPageSet object)
34  * instantiate and execute various property/list/meta modules,
35  * and assemble all resulting data into a single ApiResult object.
36  *
37  * In the generator mode, a generator will be first executed to populate a second ApiPageSet object,
38  * 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                 'usercontribs' => 'ApiQueryContributions',
78                 'watchlist' => 'ApiQueryWatchlist',
79                 'watchlistraw' => 'ApiQueryWatchlistRaw',
80                 'exturlusage' => 'ApiQueryExtLinksUsage',
81                 'users' => 'ApiQueryUsers',
82                 'random' => 'ApiQueryRandom',
83         );
84
85         private $mQueryMetaModules = array (
86                 'siteinfo' => 'ApiQuerySiteinfo',
87                 'userinfo' => 'ApiQueryUserInfo',
88                 'allmessages' => 'ApiQueryAllmessages',
89         );
90
91         private $mSlaveDB = null;
92         private $mNamedDB = array();
93
94         public function __construct($main, $action) {
95                 parent :: __construct($main, $action);
96
97                 // Allow custom modules to be added in LocalSettings.php
98                 global $wgAPIPropModules, $wgAPIListModules, $wgAPIMetaModules;
99                 self :: appendUserModules($this->mQueryPropModules, $wgAPIPropModules);
100                 self :: appendUserModules($this->mQueryListModules, $wgAPIListModules);
101                 self :: appendUserModules($this->mQueryMetaModules, $wgAPIMetaModules);
102
103                 $this->mPropModuleNames = array_keys($this->mQueryPropModules);
104                 $this->mListModuleNames = array_keys($this->mQueryListModules);
105                 $this->mMetaModuleNames = array_keys($this->mQueryMetaModules);
106
107                 // Allow the entire list of modules at first,
108                 // but during module instantiation check if it can be used as a generator.
109                 $this->mAllowedGenerators = array_merge($this->mListModuleNames, $this->mPropModuleNames);
110         }
111
112         /**
113          * Helper function to append any add-in modules to the list
114          */
115         private static function appendUserModules(&$modules, $newModules) {
116                 if (is_array( $newModules )) {
117                         foreach ( $newModules as $moduleName => $moduleClass) {
118                                 $modules[$moduleName] = $moduleClass;
119                         }
120                 }
121         }
122
123         /**
124          * Gets a default slave database connection object
125          */
126         public function getDB() {
127                 if (!isset ($this->mSlaveDB)) {
128                         $this->profileDBIn();
129                         $this->mSlaveDB = wfGetDB(DB_SLAVE,'api');
130                         $this->profileDBOut();
131                 }
132                 return $this->mSlaveDB;
133         }
134
135         /**
136          * Get the query database connection with the given name.
137          * If no such connection has been requested before, it will be created.
138          * Subsequent calls with the same $name will return the same connection
139          * as the first, regardless of $db or $groups new values.
140          */
141         public function getNamedDB($name, $db, $groups) {
142                 if (!array_key_exists($name, $this->mNamedDB)) {
143                         $this->profileDBIn();
144                         $this->mNamedDB[$name] = wfGetDB($db, $groups);
145                         $this->profileDBOut();
146                 }
147                 return $this->mNamedDB[$name];
148         }
149
150         /**
151          * Gets the set of pages the user has requested (or generated)
152          */
153         public function getPageSet() {
154                 return $this->mPageSet;
155         }
156
157         /**
158          * Get the array mapping module names to class names
159          */
160         function getModules() {
161                 return array_merge($this->mQueryPropModules, $this->mQueryListModules, $this->mQueryMetaModules);
162         }
163
164         /**
165          * Query execution happens in the following steps:
166          * #1 Create a PageSet object with any pages requested by the user
167          * #2 If using generator, execute it to get a new PageSet object
168          * #3 Instantiate all requested modules.
169          *    This way the PageSet object will know what shared data is required,
170          *    and minimize DB calls.
171          * #4 Output all normalization and redirect resolution information
172          * #5 Execute all requested modules
173          */
174         public function execute() {
175
176                 $this->params = $this->extractRequestParams();
177                 $this->redirects = $this->params['redirects'];
178
179                 //
180                 // Create PageSet
181                 //
182                 $this->mPageSet = new ApiPageSet($this, $this->redirects);
183
184                 //
185                 // Instantiate requested modules
186                 //
187                 $modules = array ();
188                 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
189                 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
190                 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
191
192                 //
193                 // If given, execute generator to substitute user supplied data with generated data.
194                 //
195                 if (isset ($this->params['generator'])) {
196                         $this->executeGeneratorModule($this->params['generator'], $modules);
197                 } else {
198                         // Append custom fields and populate page/revision information
199                         $this->addCustomFldsToPageSet($modules, $this->mPageSet);
200                         $this->mPageSet->execute();
201                 }
202
203                 //
204                 // Record page information (title, namespace, if exists, etc)
205                 //
206                 $this->outputGeneralPageInfo();
207
208                 //
209                 // Execute all requested modules.
210                 //
211                 foreach ($modules as $module) {
212                         $module->profileIn();
213                         $module->execute();
214                         wfRunHooks('APIQueryAfterExecute', array(&$module));
215                         $module->profileOut();
216                 }
217         }
218
219         /**
220          * Query modules may optimize data requests through the $this->getPageSet() object
221          * by adding extra fields from the page table.
222          * This function will gather all the extra request fields from the modules.
223          */
224         private function addCustomFldsToPageSet($modules, $pageSet) {
225                 // Query all requested modules.
226                 foreach ($modules as $module) {
227                         $module->requestExtraData($pageSet);
228                 }
229         }
230
231         /**
232          * Create instances of all modules requested by the client
233          */
234         private function InstantiateModules(&$modules, $param, $moduleList) {
235                 $list = @$this->params[$param];
236                 if (!is_null ($list))
237                         foreach ($list as $moduleName)
238                                 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
239         }
240
241         /**
242          * Appends an element for each page in the current pageSet with the most general
243          * information (id, title), plus any title normalizations and missing or invalid title/pageids/revids.
244          */
245         private function outputGeneralPageInfo() {
246
247                 $pageSet = $this->getPageSet();
248                 $result = $this->getResult();
249
250                 // Title normalizations
251                 $normValues = array ();
252                 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
253                         $normValues[] = array (
254                                 'from' => $rawTitleStr,
255                                 'to' => $titleStr
256                         );
257                 }
258
259                 if (count($normValues)) {
260                         $result->setIndexedTagName($normValues, 'n');
261                         $result->addValue('query', 'normalized', $normValues);
262                 }
263
264                 // Interwiki titles
265                 $intrwValues = array ();
266                 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
267                         $intrwValues[] = array (
268                                 'title' => $rawTitleStr,
269                                 'iw' => $interwikiStr
270                         );
271                 }
272
273                 if (count($intrwValues)) {
274                         $result->setIndexedTagName($intrwValues, 'i');
275                         $result->addValue('query', 'interwiki', $intrwValues);
276                 }
277
278                 // Show redirect information
279                 $redirValues = array ();
280                 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
281                         $redirValues[] = array (
282                                 'from' => strval($titleStrFrom),
283                                 'to' => $titleStrTo
284                         );
285                 }
286
287                 if (count($redirValues)) {
288                         $result->setIndexedTagName($redirValues, 'r');
289                         $result->addValue('query', 'redirects', $redirValues);
290                 }
291
292                 //
293                 // Missing revision elements
294                 //
295                 $missingRevIDs = $pageSet->getMissingRevisionIDs();
296                 if (count($missingRevIDs)) {
297                         $revids = array ();
298                         foreach ($missingRevIDs as $revid) {
299                                 $revids[$revid] = array (
300                                         'revid' => $revid
301                                 );
302                         }
303                         $result->setIndexedTagName($revids, 'rev');
304                         $result->addValue('query', 'badrevids', $revids);
305                 }
306
307                 //
308                 // Page elements
309                 //
310                 $pages = array ();
311
312                 // Report any missing titles
313                 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
314                         $vals = array();
315                         ApiQueryBase :: addTitleInfo($vals, $title);
316                         $vals['missing'] = '';
317                         $pages[$fakeId] = $vals;
318                 }
319                 // Report any invalid titles
320                 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
321                         $pages[$fakeId] = array('title' => $title, 'invalid' => '');
322                 // Report any missing page ids
323                 foreach ($pageSet->getMissingPageIDs() as $pageid) {
324                         $pages[$pageid] = array (
325                                 'pageid' => $pageid,
326                                 'missing' => ''
327                         );
328                 }
329
330                 // Output general page information for found titles
331                 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
332                         $vals = array();
333                         $vals['pageid'] = $pageid;
334                         ApiQueryBase :: addTitleInfo($vals, $title);
335                         $pages[$pageid] = $vals;
336                 }
337
338                 if (count($pages)) {
339
340                         if ($this->params['indexpageids']) {
341                                 $pageIDs = array_keys($pages);
342                                 // json treats all map keys as strings - converting to match
343                                 $pageIDs = array_map('strval', $pageIDs);
344                                 $result->setIndexedTagName($pageIDs, 'id');
345                                 $result->addValue('query', 'pageids', $pageIDs);
346                         }
347
348                         $result->setIndexedTagName($pages, 'page');
349                         $result->addValue('query', 'pages', $pages);
350                 }
351         }
352
353         /**
354          * For generator mode, execute generator, and use its output as new pageSet
355          */
356         protected function executeGeneratorModule($generatorName, $modules) {
357
358                 // Find class that implements requested generator
359                 if (isset ($this->mQueryListModules[$generatorName])) {
360                         $className = $this->mQueryListModules[$generatorName];
361                 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
362                         $className = $this->mQueryPropModules[$generatorName];
363                 } else {
364                         ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
365                 }
366
367                 // Generator results
368                 $resultPageSet = new ApiPageSet($this, $this->redirects);
369
370                 // Create and execute the generator
371                 $generator = new $className ($this, $generatorName);
372                 if (!$generator instanceof ApiQueryGeneratorBase)
373                         $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
374
375                 $generator->setGeneratorMode();
376
377                 // Add any additional fields modules may need
378                 $generator->requestExtraData($this->mPageSet);
379                 $this->addCustomFldsToPageSet($modules, $resultPageSet);
380
381                 // Populate page information with the original user input
382                 $this->mPageSet->execute();
383
384                 // populate resultPageSet with the generator output
385                 $generator->profileIn();
386                 $generator->executeGenerator($resultPageSet);
387                 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
388                 $resultPageSet->finishPageSetGeneration();
389                 $generator->profileOut();
390
391                 // Swap the resulting pageset back in
392                 $this->mPageSet = $resultPageSet;
393         }
394
395         /**
396          * Returns the list of allowed parameters for this module.
397          * Qurey module also lists all ApiPageSet parameters as its own.
398          */
399         public function getAllowedParams() {
400                 return array (
401                         'prop' => array (
402                                 ApiBase :: PARAM_ISMULTI => true,
403                                 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
404                         ),
405                         'list' => array (
406                                 ApiBase :: PARAM_ISMULTI => true,
407                                 ApiBase :: PARAM_TYPE => $this->mListModuleNames
408                         ),
409                         'meta' => array (
410                                 ApiBase :: PARAM_ISMULTI => true,
411                                 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
412                         ),
413                         'generator' => array (
414                                 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
415                         ),
416                         'redirects' => false,
417                         'indexpageids' => false,
418                 );
419         }
420
421         /**
422          * Override the parent to generate help messages for all available query modules.
423          */
424         public function makeHelpMsg() {
425
426                 $msg = '';
427
428                 // Make sure the internal object is empty
429                 // (just in case a sub-module decides to optimize during instantiation)
430                 $this->mPageSet = null;
431                 $this->mAllowedGenerators = array();    // Will be repopulated
432
433                 $astriks = str_repeat('--- ', 8);
434                 $astriks2 = str_repeat('*** ', 10);
435                 $msg .= "\n$astriks Query: Prop  $astriks\n\n";
436                 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
437                 $msg .= "\n$astriks Query: List  $astriks\n\n";
438                 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
439                 $msg .= "\n$astriks Query: Meta  $astriks\n\n";
440                 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
441                 $msg .= "\n\n$astriks2 Modules: continuation  $astriks2\n\n";
442
443                 // Perform the base call last because the $this->mAllowedGenerators
444                 // will be updated inside makeHelpMsgHelper()
445                 // Use parent to make default message for the query module
446                 $msg = parent :: makeHelpMsg() . $msg;
447
448                 return $msg;
449         }
450
451         /**
452          * For all modules in $moduleList, generate help messages and join them together
453          */
454         private function makeHelpMsgHelper($moduleList, $paramName) {
455
456                 $moduleDscriptions = array ();
457
458                 foreach ($moduleList as $moduleName => $moduleClass) {
459                         $module = new $moduleClass ($this, $moduleName, null);
460
461                         $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
462                         $msg2 = $module->makeHelpMsg();
463                         if ($msg2 !== false)
464                                 $msg .= $msg2;
465                         if ($module instanceof ApiQueryGeneratorBase) {
466                                 $this->mAllowedGenerators[] = $moduleName;
467                                 $msg .= "Generator:\n  This module may be used as a generator\n";
468                         }
469                         $moduleDscriptions[] = $msg;
470                 }
471
472                 return implode("\n", $moduleDscriptions);
473         }
474
475         /**
476          * Override to add extra parameters from PageSet
477          */
478         public function makeHelpMsgParameters() {
479                 $psModule = new ApiPageSet($this);
480                 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
481         }
482
483         public function shouldCheckMaxlag() {
484                 return true;
485         }
486
487         public function getParamDescription() {
488                 return array (
489                         'prop' => 'Which properties to get for the titles/revisions/pageids',
490                         'list' => 'Which lists to get',
491                         'meta' => 'Which meta data to get about the site',
492                         'generator' => 'Use the output of a list as the input for other prop/list/meta items',
493                         'redirects' => 'Automatically resolve redirects',
494                         'indexpageids' => 'Include an additional pageids section listing all returned page IDs.'
495                 );
496         }
497
498         public function getDescription() {
499                 return array (
500                         'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
501                         'and is loosely based on the Query API interface currently available on all MediaWiki servers.',
502                         'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
503                 );
504         }
505
506         protected function getExamples() {
507                 return array (
508                         'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment'
509                 );
510         }
511
512         public function getVersion() {
513                 $psModule = new ApiPageSet($this);
514                 $vers = array ();
515                 $vers[] = __CLASS__ . ': $Id: ApiQuery.php 42548 2008-10-25 14:04:43Z tstarling $';
516                 $vers[] = $psModule->getVersion();
517                 return $vers;
518         }
519 }