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