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