a03b50317fd7784dfaf9a51f0d9e8ec13ef6d2f4
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2
3 /*
4 * Created on Sep 4, 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 API class, used for both external and internal processing.
33 * When executed, it will create the requested formatter object,
34 * instantiate and execute an object associated with the needed action,
35 * and use formatter to print results.
36 * In case of an exception, an error message will be printed using the same formatter.
37 *
38 * To use API from another application, run it using FauxRequest object, in which
39 * case any internal exceptions will not be handled but passed up to the caller.
40 * After successful execution, use getResult() for the resulting data.
41 *
42 * @addtogroup API
43 */
44 class ApiMain extends ApiBase {
45
46 /**
47 * When no format parameter is given, this format will be used
48 */
49 const API_DEFAULT_FORMAT = 'xmlfm';
50
51 /**
52 * List of available modules: action name => module class
53 */
54 private static $Modules = array (
55 'login' => 'ApiLogin',
56 'query' => 'ApiQuery',
57 'opensearch' => 'ApiOpenSearch',
58 'feedwatchlist' => 'ApiFeedWatchlist',
59 'help' => 'ApiHelp',
60 );
61
62 /**
63 * List of available formats: format name => format class
64 */
65 private static $Formats = array (
66 'json' => 'ApiFormatJson',
67 'jsonfm' => 'ApiFormatJson',
68 'php' => 'ApiFormatPhp',
69 'phpfm' => 'ApiFormatPhp',
70 'wddx' => 'ApiFormatWddx',
71 'wddxfm' => 'ApiFormatWddx',
72 'xml' => 'ApiFormatXml',
73 'xmlfm' => 'ApiFormatXml',
74 'yaml' => 'ApiFormatYaml',
75 'yamlfm' => 'ApiFormatYaml',
76 'rawfm' => 'ApiFormatJson'
77 );
78
79 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
80 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
81
82 /**
83 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
84 *
85 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
86 * @param $enableWrite bool should be set to true if the api may modify data
87 */
88 public function __construct($request, $enableWrite = false) {
89
90 $this->mInternalMode = ($request instanceof FauxRequest);
91
92 // Special handling for the main module: $parent === $this
93 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
94
95 if (!$this->mInternalMode) {
96
97 // Impose module restrictions.
98 // If the current user cannot read,
99 // Remove all modules other than login & help
100 global $wgUser, $wgWhitelistRead;
101 if (!$wgUser->isAllowed('read')) {
102 self::$Modules = array(
103 'login' => self::$Modules['login'],
104 'help' => self::$Modules['help']
105 );
106 }
107 }
108
109 $this->mModules = self :: $Modules;
110 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
111 $this->mFormats = self :: $Formats;
112 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
113
114 $this->mResult = new ApiResult($this);
115 $this->mShowVersions = false;
116 $this->mEnableWrite = $enableWrite;
117
118 $this->mRequest = & $request;
119
120 $this->mSquidMaxage = 0;
121 }
122
123 /**
124 * Return the request object that contains client's request
125 */
126 public function getRequest() {
127 return $this->mRequest;
128 }
129
130 /**
131 * Get the ApiResult object asscosiated with current request
132 */
133 public function getResult() {
134 return $this->mResult;
135 }
136
137 /**
138 * This method will simply cause an error if the write mode was disabled for this api.
139 */
140 public function requestWriteMode() {
141 if (!$this->mEnableWrite)
142 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
143 'statement is included in the site\'s LocalSettings.php file', 'readonly');
144 }
145
146 /**
147 * Set how long the response should be cached.
148 */
149 public function setCacheMaxAge($maxage) {
150 $this->mSquidMaxage = $maxage;
151 }
152
153 /**
154 * Create an instance of an output formatter by its name
155 */
156 public function createPrinterByName($format) {
157 return new $this->mFormats[$format] ($this, $format);
158 }
159
160 /**
161 * Execute api request. Any errors will be handled if the API was called by the remote client.
162 */
163 public function execute() {
164 $this->profileIn();
165 if ($this->mInternalMode)
166 $this->executeAction();
167 else
168 $this->executeActionWithErrorHandling();
169 $this->profileOut();
170 }
171
172 /**
173 * Execute an action, and in case of an error, erase whatever partial results
174 * have been accumulated, and replace it with an error message and a help screen.
175 */
176 protected function executeActionWithErrorHandling() {
177
178 // In case an error occurs during data output,
179 // clear the output buffer and print just the error information
180 ob_start();
181
182 try {
183 $this->executeAction();
184 } catch (Exception $e) {
185 //
186 // Handle any kind of exception by outputing properly formatted error message.
187 // If this fails, an unhandled exception should be thrown so that global error
188 // handler will process and log it.
189 //
190
191 // Error results should not be cached
192 $this->setCacheMaxAge(0);
193
194 // Printer may not be initialized if the extractRequestParams() fails for the main module
195 if (!isset ($this->mPrinter)) {
196 // The printer has not been created yet. Try to manually get formatter value.
197 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
198 if (!in_array($value, $this->mFormatNames))
199 $value = self::API_DEFAULT_FORMAT;
200
201 $this->mPrinter = $this->createPrinterByName($value);
202 if ($this->mPrinter->getNeedsRawData())
203 $this->getResult()->setRawMode();
204 }
205
206 if ($e instanceof UsageException) {
207 //
208 // User entered incorrect parameters - print usage screen
209 //
210 $errMessage = array (
211 'code' => $e->getCodeString(), 'info' => $e->getMessage());
212
213 // Only print the help message when this is for the developer, not runtime
214 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
215 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
216
217 } else {
218 //
219 // Something is seriously wrong
220 //
221 $errMessage = array (
222 'code' => 'internal_api_error',
223 'info' => "Exception Caught: {$e->getMessage()}"
224 );
225 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
226 }
227
228 $headerStr = 'MediaWiki-API-Error: ' . $errMessage['code'];
229 if ($e->getCode() === 0)
230 header($headerStr, true);
231 else
232 header($headerStr, true, $e->getCode());
233
234 // Reset and print just the error message
235 ob_clean();
236 $this->getResult()->reset();
237 $this->getResult()->addValue(null, 'error', $errMessage);
238
239 // If the error occured during printing, do a printer->profileOut()
240 $this->mPrinter->safeProfileOut();
241 $this->printResult(true);
242 }
243
244 // Set the cache expiration at the last moment, as any errors may change the expiration.
245 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
246 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
247 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
248 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
249
250 if($this->mPrinter->getIsHtml())
251 echo wfReportTime();
252
253 ob_end_flush();
254 }
255
256 /**
257 * Execute the actual module, without any error handling
258 */
259 protected function executeAction() {
260
261 $params = $this->extractRequestParams();
262
263 $this->mShowVersions = $params['version'];
264 $this->mAction = $params['action'];
265
266 // Instantiate the module requested by the user
267 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
268
269 if (!$this->mInternalMode) {
270
271 // See if custom printer is used
272 $this->mPrinter = $module->getCustomPrinter();
273 if (is_null($this->mPrinter)) {
274 // Create an appropriate printer
275 $this->mPrinter = $this->createPrinterByName($params['format']);
276 }
277
278 if ($this->mPrinter->getNeedsRawData())
279 $this->getResult()->setRawMode();
280 }
281
282 // Execute
283 $module->profileIn();
284 $module->execute();
285 $module->profileOut();
286
287 if (!$this->mInternalMode) {
288 // Print result data
289 $this->printResult(false);
290 }
291 }
292
293 /**
294 * Print results using the current printer
295 */
296 protected function printResult($isError) {
297 $printer = $this->mPrinter;
298 $printer->profileIn();
299 $printer->initPrinter($isError);
300 $printer->execute();
301 $printer->closePrinter();
302 $printer->profileOut();
303 }
304
305 /**
306 * See ApiBase for description.
307 */
308 protected function getAllowedParams() {
309 return array (
310 'format' => array (
311 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
312 ApiBase :: PARAM_TYPE => $this->mFormatNames
313 ),
314 'action' => array (
315 ApiBase :: PARAM_DFLT => 'help',
316 ApiBase :: PARAM_TYPE => $this->mModuleNames
317 ),
318 'version' => false
319 );
320 }
321
322 /**
323 * See ApiBase for description.
324 */
325 protected function getParamDescription() {
326 return array (
327 'format' => 'The format of the output',
328 'action' => 'What action you would like to perform',
329 'version' => 'When showing help, include version for each module'
330 );
331 }
332
333 /**
334 * See ApiBase for description.
335 */
336 protected function getDescription() {
337 return array (
338 '',
339 '',
340 '******************************************************************',
341 '** **',
342 '** This is an auto-generated MediaWiki API documentation page **',
343 '** **',
344 '** Documentation and Examples: **',
345 '** http://www.mediawiki.org/wiki/API **',
346 '** **',
347 '******************************************************************',
348 '',
349 'Status: All features shown on this page should be working, but the API',
350 ' is still in active development, and may change at any time.',
351 ' Make sure to monitor our mailing list for any updates.',
352 '',
353 'Documentation: http://www.mediawiki.org/wiki/API',
354 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
355 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
356 '',
357 '',
358 '',
359 '',
360 '',
361 );
362 }
363
364 /**
365 * Returns an array of strings with credits for the API
366 */
367 protected function getCredits() {
368 return array(
369 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
370 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
371 );
372 }
373
374 /**
375 * Override the parent to generate help messages for all available modules.
376 */
377 public function makeHelpMsg() {
378
379 // Use parent to make default message for the main module
380 $msg = parent :: makeHelpMsg();
381
382 $astriks = str_repeat('*** ', 10);
383 $msg .= "\n\n$astriks Modules $astriks\n\n";
384 foreach( $this->mModules as $moduleName => $unused ) {
385 $module = new $this->mModules[$moduleName] ($this, $moduleName);
386 $msg .= self::makeHelpMsgHeader($module, 'action');
387 $msg2 = $module->makeHelpMsg();
388 if ($msg2 !== false)
389 $msg .= $msg2;
390 $msg .= "\n";
391 }
392
393 $msg .= "\n$astriks Formats $astriks\n\n";
394 foreach( $this->mFormats as $formatName => $unused ) {
395 $module = $this->createPrinterByName($formatName);
396 $msg .= self::makeHelpMsgHeader($module, 'format');
397 $msg2 = $module->makeHelpMsg();
398 if ($msg2 !== false)
399 $msg .= $msg2;
400 $msg .= "\n";
401 }
402
403 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
404
405
406 return $msg;
407 }
408
409 public static function makeHelpMsgHeader($module, $paramName) {
410 $modulePrefix = $module->getModulePrefix();
411 if (!empty($modulePrefix))
412 $modulePrefix = "($modulePrefix) ";
413
414 return "* $paramName={$module->getModuleName()} $modulePrefix*";
415 }
416
417 private $mIsBot = null;
418
419 private $mIsSysop = null;
420
421 /**
422 * Returns true if the currently logged in user is a bot, false otherwise
423 */
424 public function isBot() {
425 if (!isset ($this->mIsBot)) {
426 global $wgUser;
427 $this->mIsBot = $wgUser->isAllowed('bot');
428 }
429 return $this->mIsBot;
430 }
431
432 /**
433 * Similar to isBot(), this method returns true if the logged in user is
434 * a sysop, and false if not.
435 */
436 public function isSysop() {
437 if (!isset ($this->mIsSysop)) {
438 global $wgUser;
439 $this->mIsSysop = in_array( 'sysop',
440 $wgUser->getGroups());
441 }
442
443 return $this->mIsSysop;
444 }
445
446 public function getShowVersions() {
447 return $this->mShowVersions;
448 }
449
450 /**
451 * Returns the version information of this file, plus it includes
452 * the versions for all files that are not callable proper API modules
453 */
454 public function getVersion() {
455 $vers = array ();
456 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
457 $vers[] = __CLASS__ . ': $Id$';
458 $vers[] = ApiBase :: getBaseVersion();
459 $vers[] = ApiFormatBase :: getBaseVersion();
460 $vers[] = ApiQueryBase :: getBaseVersion();
461 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
462 return $vers;
463 }
464 }
465
466 /**
467 * This exception will be thrown when dieUsage is called to stop module execution.
468 * The exception handling code will print a help screen explaining how this API may be used.
469 *
470 * @addtogroup API
471 */
472 class UsageException extends Exception {
473
474 private $mCodestr;
475
476 public function __construct($message, $codestr, $code = 0) {
477 parent :: __construct($message, $code);
478 $this->mCodestr = $codestr;
479 }
480 public function getCodeString() {
481 return $this->mCodestr;
482 }
483 public function __toString() {
484 return "{$this->getCodeString()}: {$this->getMessage()}";
485 }
486 }
487