forget to shutdown classes in ApiQuery.php
[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 (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 #'brokenredirects' => 'ApiQueryBrokenRedirects',
71 'categorymembers' => 'ApiQueryCategoryMembers',
72 #'doubleredirects' => 'ApiQueryDoubleRedirects',
73 'deletedrevs' => 'ApiQueryDeletedrevs',
74 'embeddedin' => 'ApiQueryBacklinks',
75 'imageusage' => 'ApiQueryBacklinks',
76 'logevents' => 'ApiQueryLogEvents',
77 'recentchanges' => 'ApiQueryRecentChanges',
78 'search' => 'ApiQuerySearch',
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 public function getCustomPrinter() {
177 // If &exportnowrap is set, use the raw formatter
178 if ($this->getParameter('export') &&
179 $this->getParameter('exportnowrap'))
180 return new ApiFormatRaw($this->getMain(),
181 $this->getMain()->createPrinterByName('xml'));
182 else
183 return null;
184 }
185
186 /**
187 * Query execution happens in the following steps:
188 * #1 Create a PageSet object with any pages requested by the user
189 * #2 If using a generator, execute it to get a new ApiPageSet object
190 * #3 Instantiate all requested modules.
191 * This way the PageSet object will know what shared data is required,
192 * and minimize DB calls.
193 * #4 Output all normalization and redirect resolution information
194 * #5 Execute all requested modules
195 */
196 public function execute() {
197
198 $this->params = $this->extractRequestParams();
199 $this->redirects = $this->params['redirects'];
200
201 //
202 // Create PageSet
203 //
204 $this->mPageSet = new ApiPageSet($this, $this->redirects);
205
206 //
207 // Instantiate requested modules
208 //
209 $modules = array ();
210 $this->InstantiateModules($modules, 'prop', $this->mQueryPropModules);
211 $this->InstantiateModules($modules, 'list', $this->mQueryListModules);
212 $this->InstantiateModules($modules, 'meta', $this->mQueryMetaModules);
213
214 //
215 // If given, execute generator to substitute user supplied data with generated data.
216 //
217 if (isset ($this->params['generator'])) {
218 $this->executeGeneratorModule($this->params['generator'], $modules);
219 } else {
220 // Append custom fields and populate page/revision information
221 $this->addCustomFldsToPageSet($modules, $this->mPageSet);
222 $this->mPageSet->execute();
223 }
224
225 //
226 // Record page information (title, namespace, if exists, etc)
227 //
228 $this->outputGeneralPageInfo();
229
230 //
231 // Execute all requested modules.
232 //
233 foreach ($modules as $module) {
234 $module->profileIn();
235 $module->execute();
236 wfRunHooks('APIQueryAfterExecute', array(&$module));
237 $module->profileOut();
238 }
239 }
240
241 /**
242 * Query modules may optimize data requests through the $this->getPageSet() object
243 * by adding extra fields from the page table.
244 * This function will gather all the extra request fields from the modules.
245 * @param $modules array of module objects
246 * @param $pageSet ApiPageSet
247 */
248 private function addCustomFldsToPageSet($modules, $pageSet) {
249 // Query all requested modules.
250 foreach ($modules as $module) {
251 $module->requestExtraData($pageSet);
252 }
253 }
254
255 /**
256 * Create instances of all modules requested by the client
257 * @param $modules array to append instatiated modules to
258 * @param $param string Parameter name to read modules from
259 * @param $moduleList array(modulename => classname)
260 */
261 private function InstantiateModules(&$modules, $param, $moduleList) {
262 $list = @$this->params[$param];
263 if (!is_null ($list))
264 foreach ($list as $moduleName)
265 $modules[] = new $moduleList[$moduleName] ($this, $moduleName);
266 }
267
268 /**
269 * Appends an element for each page in the current pageSet with the
270 * most general information (id, title), plus any title normalizations
271 * and missing or invalid title/pageids/revids.
272 */
273 private function outputGeneralPageInfo() {
274
275 $pageSet = $this->getPageSet();
276 $result = $this->getResult();
277
278 # We don't check for a full result set here because we can't be adding
279 # more than 380K. The maximum revision size is in the megabyte range,
280 # and the maximum result size must be even higher than that.
281
282 // Title normalizations
283 $normValues = array ();
284 foreach ($pageSet->getNormalizedTitles() as $rawTitleStr => $titleStr) {
285 $normValues[] = array (
286 'from' => $rawTitleStr,
287 'to' => $titleStr
288 );
289 }
290
291 if (count($normValues)) {
292 $result->setIndexedTagName($normValues, 'n');
293 $result->addValue('query', 'normalized', $normValues);
294 }
295
296 // Interwiki titles
297 $intrwValues = array ();
298 foreach ($pageSet->getInterwikiTitles() as $rawTitleStr => $interwikiStr) {
299 $intrwValues[] = array (
300 'title' => $rawTitleStr,
301 'iw' => $interwikiStr
302 );
303 }
304
305 if (count($intrwValues)) {
306 $result->setIndexedTagName($intrwValues, 'i');
307 $result->addValue('query', 'interwiki', $intrwValues);
308 }
309
310 // Show redirect information
311 $redirValues = array ();
312 foreach ($pageSet->getRedirectTitles() as $titleStrFrom => $titleStrTo) {
313 $redirValues[] = array (
314 'from' => strval($titleStrFrom),
315 'to' => $titleStrTo
316 );
317 }
318
319 if (count($redirValues)) {
320 $result->setIndexedTagName($redirValues, 'r');
321 $result->addValue('query', 'redirects', $redirValues);
322 }
323
324 //
325 // Missing revision elements
326 //
327 $missingRevIDs = $pageSet->getMissingRevisionIDs();
328 if (count($missingRevIDs)) {
329 $revids = array ();
330 foreach ($missingRevIDs as $revid) {
331 $revids[$revid] = array (
332 'revid' => $revid
333 );
334 }
335 $result->setIndexedTagName($revids, 'rev');
336 $result->addValue('query', 'badrevids', $revids);
337 }
338
339 //
340 // Page elements
341 //
342 $pages = array ();
343
344 // Report any missing titles
345 foreach ($pageSet->getMissingTitles() as $fakeId => $title) {
346 $vals = array();
347 ApiQueryBase :: addTitleInfo($vals, $title);
348 $vals['missing'] = '';
349 $pages[$fakeId] = $vals;
350 }
351 // Report any invalid titles
352 foreach ($pageSet->getInvalidTitles() as $fakeId => $title)
353 $pages[$fakeId] = array('title' => $title, 'invalid' => '');
354 // Report any missing page ids
355 foreach ($pageSet->getMissingPageIDs() as $pageid) {
356 $pages[$pageid] = array (
357 'pageid' => $pageid,
358 'missing' => ''
359 );
360 }
361
362 // Output general page information for found titles
363 foreach ($pageSet->getGoodTitles() as $pageid => $title) {
364 $vals = array();
365 $vals['pageid'] = $pageid;
366 ApiQueryBase :: addTitleInfo($vals, $title);
367 $pages[$pageid] = $vals;
368 }
369
370 if (count($pages)) {
371
372 if ($this->params['indexpageids']) {
373 $pageIDs = array_keys($pages);
374 // json treats all map keys as strings - converting to match
375 $pageIDs = array_map('strval', $pageIDs);
376 $result->setIndexedTagName($pageIDs, 'id');
377 $result->addValue('query', 'pageids', $pageIDs);
378 }
379
380 $result->setIndexedTagName($pages, 'page');
381 $result->addValue('query', 'pages', $pages);
382 }
383 if ($this->params['export']) {
384 $exporter = new WikiExporter($this->getDB());
385 // WikiExporter writes to stdout, so catch its
386 // output with an ob
387 ob_start();
388 $exporter->openStream();
389 foreach (@$pageSet->getGoodTitles() as $title)
390 if ($title->userCanRead())
391 $exporter->pageByTitle($title);
392 $exporter->closeStream();
393 $exportxml = ob_get_contents();
394 ob_end_clean();
395 // Don't check the size of exported stuff
396 // It's not continuable, so it would cause more
397 // problems than it'd solve
398 $result->disableSizeCheck();
399 if ($this->params['exportnowrap']) {
400 $result->reset();
401 // Raw formatter will handle this
402 $result->addValue(null, 'text', $exportxml);
403 $result->addValue(null, 'mime', 'text/xml');
404 } else {
405 $r = array();
406 ApiResult::setContent($r, $exportxml);
407 $result->addValue('query', 'export', $r);
408 }
409 $result->enableSizeCheck();
410 }
411 }
412
413 /**
414 * For generator mode, execute generator, and use its output as new
415 * ApiPageSet
416 * @param $generatorName string Module name
417 * @param $modules array of module objects
418 */
419 protected function executeGeneratorModule($generatorName, $modules) {
420
421 // Find class that implements requested generator
422 if (isset ($this->mQueryListModules[$generatorName])) {
423 $className = $this->mQueryListModules[$generatorName];
424 } elseif (isset ($this->mQueryPropModules[$generatorName])) {
425 $className = $this->mQueryPropModules[$generatorName];
426 } else {
427 ApiBase :: dieDebug(__METHOD__, "Unknown generator=$generatorName");
428 }
429
430 // Generator results
431 $resultPageSet = new ApiPageSet($this, $this->redirects);
432
433 // Create and execute the generator
434 $generator = new $className ($this, $generatorName);
435 if (!$generator instanceof ApiQueryGeneratorBase)
436 $this->dieUsage("Module $generatorName cannot be used as a generator", "badgenerator");
437
438 $generator->setGeneratorMode();
439
440 // Add any additional fields modules may need
441 $generator->requestExtraData($this->mPageSet);
442 $this->addCustomFldsToPageSet($modules, $resultPageSet);
443
444 // Populate page information with the original user input
445 $this->mPageSet->execute();
446
447 // populate resultPageSet with the generator output
448 $generator->profileIn();
449 $generator->executeGenerator($resultPageSet);
450 wfRunHooks('APIQueryGeneratorAfterExecute', array(&$generator, &$resultPageSet));
451 $resultPageSet->finishPageSetGeneration();
452 $generator->profileOut();
453
454 // Swap the resulting pageset back in
455 $this->mPageSet = $resultPageSet;
456 }
457
458 public function getAllowedParams() {
459 return array (
460 'prop' => array (
461 ApiBase :: PARAM_ISMULTI => true,
462 ApiBase :: PARAM_TYPE => $this->mPropModuleNames
463 ),
464 'list' => array (
465 ApiBase :: PARAM_ISMULTI => true,
466 ApiBase :: PARAM_TYPE => $this->mListModuleNames
467 ),
468 'meta' => array (
469 ApiBase :: PARAM_ISMULTI => true,
470 ApiBase :: PARAM_TYPE => $this->mMetaModuleNames
471 ),
472 'generator' => array (
473 ApiBase :: PARAM_TYPE => $this->mAllowedGenerators
474 ),
475 'redirects' => false,
476 'indexpageids' => false,
477 'export' => false,
478 'exportnowrap' => false,
479 );
480 }
481
482 /**
483 * Override the parent to generate help messages for all available query modules.
484 * @return string
485 */
486 public function makeHelpMsg() {
487
488 $msg = '';
489
490 // Make sure the internal object is empty
491 // (just in case a sub-module decides to optimize during instantiation)
492 $this->mPageSet = null;
493 $this->mAllowedGenerators = array(); // Will be repopulated
494
495 $astriks = str_repeat('--- ', 8);
496 $astriks2 = str_repeat('*** ', 10);
497 $msg .= "\n$astriks Query: Prop $astriks\n\n";
498 $msg .= $this->makeHelpMsgHelper($this->mQueryPropModules, 'prop');
499 $msg .= "\n$astriks Query: List $astriks\n\n";
500 $msg .= $this->makeHelpMsgHelper($this->mQueryListModules, 'list');
501 $msg .= "\n$astriks Query: Meta $astriks\n\n";
502 $msg .= $this->makeHelpMsgHelper($this->mQueryMetaModules, 'meta');
503 $msg .= "\n\n$astriks2 Modules: continuation $astriks2\n\n";
504
505 // Perform the base call last because the $this->mAllowedGenerators
506 // will be updated inside makeHelpMsgHelper()
507 // Use parent to make default message for the query module
508 $msg = parent :: makeHelpMsg() . $msg;
509
510 return $msg;
511 }
512
513 /**
514 * For all modules in $moduleList, generate help messages and join them together
515 * @param $moduleList array(modulename => classname)
516 * @param $paramName string Parameter name
517 * @return string
518 */
519 private function makeHelpMsgHelper($moduleList, $paramName) {
520
521 $moduleDescriptions = array ();
522
523 foreach ($moduleList as $moduleName => $moduleClass) {
524 $module = new $moduleClass ($this, $moduleName, null);
525
526 $msg = ApiMain::makeHelpMsgHeader($module, $paramName);
527 $msg2 = $module->makeHelpMsg();
528 if ($msg2 !== false)
529 $msg .= $msg2;
530 if ($module instanceof ApiQueryGeneratorBase) {
531 $this->mAllowedGenerators[] = $moduleName;
532 $msg .= "Generator:\n This module may be used as a generator\n";
533 }
534 $moduleDescriptions[] = $msg;
535 }
536
537 return implode("\n", $moduleDescriptions);
538 }
539
540 /**
541 * Override to add extra parameters from PageSet
542 * @return string
543 */
544 public function makeHelpMsgParameters() {
545 $psModule = new ApiPageSet($this);
546 return $psModule->makeHelpMsgParameters() . parent :: makeHelpMsgParameters();
547 }
548
549 public function shouldCheckMaxlag() {
550 return true;
551 }
552
553 public function getParamDescription() {
554 return array (
555 'prop' => 'Which properties to get for the titles/revisions/pageids',
556 'list' => 'Which lists to get',
557 'meta' => 'Which meta data to get about the site',
558 'generator' => array('Use the output of a list as the input for other prop/list/meta items',
559 'NOTE: generator parameter names must be prefixed with a \'g\', see examples.'),
560 'redirects' => 'Automatically resolve redirects',
561 'indexpageids' => 'Include an additional pageids section listing all returned page IDs.',
562 'export' => 'Export the current revisions of all given or generated pages',
563 'exportnowrap' => 'Return the export XML without wrapping it in an XML result (same format as Special:Export). Can only be used with export',
564 );
565 }
566
567 public function getDescription() {
568 return array (
569 'Query API module allows applications to get needed pieces of data from the MediaWiki databases,',
570 'and is loosely based on the old query.php interface.',
571 'All data modifications will first have to use query to acquire a token to prevent abuse from malicious sites.'
572 );
573 }
574
575 protected function getExamples() {
576 return array (
577 'api.php?action=query&prop=revisions&meta=siteinfo&titles=Main%20Page&rvprop=user|comment',
578 'api.php?action=query&generator=allpages&gapprefix=API/&prop=revisions',
579 );
580 }
581
582 public function getVersion() {
583 $psModule = new ApiPageSet($this);
584 $vers = array ();
585 $vers[] = __CLASS__ . ': $Id$';
586 $vers[] = $psModule->getVersion();
587 return $vers;
588 }
589 }