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