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