Tweak two messages: add warnings "for experts only".
[mediawiki.git] / includes / api / ApiMain.php
blobc8a663722bb204a174f6d3e178242040fd9dcb64
1 <?php
3 /*
4 * Created on Sep 4, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
31 /**
32 * @defgroup API API
35 /**
36 * This is the main API class, used for both external and internal processing.
37 * When executed, it will create the requested formatter object,
38 * instantiate and execute an object associated with the needed action,
39 * and use formatter to print results.
40 * In case of an exception, an error message will be printed using the same formatter.
42 * To use API from another application, run it using FauxRequest object, in which
43 * case any internal exceptions will not be handled but passed up to the caller.
44 * After successful execution, use getResult() for the resulting data.
46 * @ingroup API
48 class ApiMain extends ApiBase {
50 /**
51 * When no format parameter is given, this format will be used
53 const API_DEFAULT_FORMAT = 'xmlfm';
55 /**
56 * List of available modules: action name => module class
58 private static $Modules = array (
59 'login' => 'ApiLogin',
60 'logout' => 'ApiLogout',
61 'query' => 'ApiQuery',
62 'expandtemplates' => 'ApiExpandTemplates',
63 'parse' => 'ApiParse',
64 'opensearch' => 'ApiOpenSearch',
65 'feedwatchlist' => 'ApiFeedWatchlist',
66 'help' => 'ApiHelp',
67 'paraminfo' => 'ApiParamInfo',
70 private static $WriteModules = array (
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
77 'move' => 'ApiMove',
78 'edit' => 'ApiEditPage',
79 'emailuser' => 'ApiEmailUser',
82 /**
83 * List of available formats: format name => format class
85 private static $Formats = array (
86 'json' => 'ApiFormatJson',
87 'jsonfm' => 'ApiFormatJson',
88 'php' => 'ApiFormatPhp',
89 'phpfm' => 'ApiFormatPhp',
90 'wddx' => 'ApiFormatWddx',
91 'wddxfm' => 'ApiFormatWddx',
92 'xml' => 'ApiFormatXml',
93 'xmlfm' => 'ApiFormatXml',
94 'yaml' => 'ApiFormatYaml',
95 'yamlfm' => 'ApiFormatYaml',
96 'rawfm' => 'ApiFormatJson',
97 'txt' => 'ApiFormatTxt',
98 'txtfm' => 'ApiFormatTxt',
99 'dbg' => 'ApiFormatDbg',
100 'dbgfm' => 'ApiFormatDbg'
103 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
104 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
107 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
109 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
110 * @param $enableWrite bool should be set to true if the api may modify data
112 public function __construct($request, $enableWrite = false) {
114 $this->mInternalMode = ($request instanceof FauxRequest);
116 // Special handling for the main module: $parent === $this
117 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
119 if (!$this->mInternalMode) {
121 // Impose module restrictions.
122 // If the current user cannot read,
123 // Remove all modules other than login
124 global $wgUser;
126 if( $request->getVal( 'callback' ) !== null ) {
127 // JSON callback allows cross-site reads.
128 // For safety, strip user credentials.
129 wfDebug( "API: stripping user credentials for JSON callback\n" );
130 $wgUser = new User();
133 if (!$wgUser->isAllowed('read')) {
134 self::$Modules = array(
135 'login' => self::$Modules['login'],
136 'logout' => self::$Modules['logout'],
137 'help' => self::$Modules['help'],
142 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
143 $this->mModules = $wgAPIModules + self :: $Modules;
144 if($wgEnableWriteAPI)
145 $this->mModules += self::$WriteModules;
147 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
148 $this->mFormats = self :: $Formats;
149 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
151 $this->mResult = new ApiResult($this);
152 $this->mShowVersions = false;
153 $this->mEnableWrite = $enableWrite;
155 $this->mRequest = & $request;
157 $this->mSquidMaxage = 0;
158 $this->mCommit = false;
162 * Return true if the API was started by other PHP code using FauxRequest
164 public function isInternalMode() {
165 return $this->mInternalMode;
169 * Return the request object that contains client's request
171 public function getRequest() {
172 return $this->mRequest;
176 * Get the ApiResult object asscosiated with current request
178 public function getResult() {
179 return $this->mResult;
183 * This method will simply cause an error if the write mode was disabled
184 * or if the current user doesn't have the right to use it
186 public function requestWriteMode() {
187 global $wgUser;
188 if (!$this->mEnableWrite)
189 $this->dieUsage('Editing of this wiki through the API' .
190 ' is disabled. Make sure the $wgEnableWriteAPI=true; ' .
191 'statement is included in the wiki\'s ' .
192 'LocalSettings.php file', 'noapiwrite');
193 if (!$wgUser->isAllowed('writeapi'))
194 $this->dieUsage('You\'re not allowed to edit this ' .
195 'wiki through the API', 'writeapidenied');
199 * Set how long the response should be cached.
201 public function setCacheMaxAge($maxage) {
202 $this->mSquidMaxage = $maxage;
206 * Create an instance of an output formatter by its name
208 public function createPrinterByName($format) {
209 return new $this->mFormats[$format] ($this, $format);
213 * Execute api request. Any errors will be handled if the API was called by the remote client.
215 public function execute() {
216 $this->profileIn();
217 if ($this->mInternalMode)
218 $this->executeAction();
219 else
220 $this->executeActionWithErrorHandling();
222 $this->profileOut();
226 * Execute an action, and in case of an error, erase whatever partial results
227 * have been accumulated, and replace it with an error message and a help screen.
229 protected function executeActionWithErrorHandling() {
231 // In case an error occurs during data output,
232 // clear the output buffer and print just the error information
233 ob_start();
235 try {
236 $this->executeAction();
237 } catch (Exception $e) {
239 // Handle any kind of exception by outputing properly formatted error message.
240 // If this fails, an unhandled exception should be thrown so that global error
241 // handler will process and log it.
244 $errCode = $this->substituteResultWithError($e);
246 // Error results should not be cached
247 $this->setCacheMaxAge(0);
249 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
250 if ($e->getCode() === 0)
251 header($headerStr, true);
252 else
253 header($headerStr, true, $e->getCode());
255 // Reset and print just the error message
256 ob_clean();
258 // If the error occured during printing, do a printer->profileOut()
259 $this->mPrinter->safeProfileOut();
260 $this->printResult(true);
263 // Set the cache expiration at the last moment, as any errors may change the expiration.
264 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
265 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
266 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
267 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
269 if($this->mPrinter->getIsHtml())
270 echo wfReportTime();
272 ob_end_flush();
276 * Replace the result data with the information about an exception.
277 * Returns the error code
279 protected function substituteResultWithError($e) {
281 // Printer may not be initialized if the extractRequestParams() fails for the main module
282 if (!isset ($this->mPrinter)) {
283 // The printer has not been created yet. Try to manually get formatter value.
284 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
285 if (!in_array($value, $this->mFormatNames))
286 $value = self::API_DEFAULT_FORMAT;
288 $this->mPrinter = $this->createPrinterByName($value);
289 if ($this->mPrinter->getNeedsRawData())
290 $this->getResult()->setRawMode();
293 if ($e instanceof UsageException) {
295 // User entered incorrect parameters - print usage screen
297 $errMessage = array (
298 'code' => $e->getCodeString(),
299 'info' => $e->getMessage());
301 // Only print the help message when this is for the developer, not runtime
302 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
303 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
305 } else {
307 // Something is seriously wrong
309 $errMessage = array (
310 'code' => 'internal_api_error_'. get_class($e),
311 'info' => "Exception Caught: {$e->getMessage()}"
313 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
316 $this->getResult()->reset();
317 $this->getResult()->addValue(null, 'error', $errMessage);
319 return $errMessage['code'];
323 * Execute the actual module, without any error handling
325 protected function executeAction() {
327 $params = $this->extractRequestParams();
329 $this->mShowVersions = $params['version'];
330 $this->mAction = $params['action'];
332 // Instantiate the module requested by the user
333 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
335 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
336 // Check for maxlag
337 global $wgShowHostnames;
338 $maxLag = $params['maxlag'];
339 list( $host, $lag ) = wfGetLB()->getMaxLag();
340 if ( $lag > $maxLag ) {
341 if( $wgShowHostnames ) {
342 ApiBase :: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
343 } else {
344 ApiBase :: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
346 return;
350 if (!$this->mInternalMode) {
351 // Ignore mustBePosted() for internal calls
352 if($module->mustBePosted() && !$this->mRequest->wasPosted())
353 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
355 // See if custom printer is used
356 $this->mPrinter = $module->getCustomPrinter();
357 if (is_null($this->mPrinter)) {
358 // Create an appropriate printer
359 $this->mPrinter = $this->createPrinterByName($params['format']);
362 if ($this->mPrinter->getNeedsRawData())
363 $this->getResult()->setRawMode();
366 // Execute
367 $module->profileIn();
368 $module->execute();
369 $module->profileOut();
371 if (!$this->mInternalMode) {
372 // Print result data
373 $this->printResult(false);
378 * Print results using the current printer
380 protected function printResult($isError) {
381 $printer = $this->mPrinter;
382 $printer->profileIn();
384 /* If the help message is requested in the default (xmlfm) format,
385 * tell the printer not to escape ampersands so that our links do
386 * not break. */
387 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
388 && $this->getParameter('format') == ApiMain::API_DEFAULT_FORMAT );
390 $printer->initPrinter($isError);
392 $printer->execute();
393 $printer->closePrinter();
394 $printer->profileOut();
398 * See ApiBase for description.
400 public function getAllowedParams() {
401 return array (
402 'format' => array (
403 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
404 ApiBase :: PARAM_TYPE => $this->mFormatNames
406 'action' => array (
407 ApiBase :: PARAM_DFLT => 'help',
408 ApiBase :: PARAM_TYPE => $this->mModuleNames
410 'version' => false,
411 'maxlag' => array (
412 ApiBase :: PARAM_TYPE => 'integer'
418 * See ApiBase for description.
420 public function getParamDescription() {
421 return array (
422 'format' => 'The format of the output',
423 'action' => 'What action you would like to perform',
424 'version' => 'When showing help, include version for each module',
425 'maxlag' => 'Maximum lag'
430 * See ApiBase for description.
432 public function getDescription() {
433 return array (
436 '******************************************************************',
437 '** **',
438 '** This is an auto-generated MediaWiki API documentation page **',
439 '** **',
440 '** Documentation and Examples: **',
441 '** http://www.mediawiki.org/wiki/API **',
442 '** **',
443 '******************************************************************',
445 'Status: All features shown on this page should be working, but the API',
446 ' is still in active development, and may change at any time.',
447 ' Make sure to monitor our mailing list for any updates.',
449 'Documentation: http://www.mediawiki.org/wiki/API',
450 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
451 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
461 * Returns an array of strings with credits for the API
463 protected function getCredits() {
464 return array(
465 'API developers:',
466 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
467 ' Victor Vasiliev - vasilvv at gee mail dot com',
468 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
470 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
471 'or file a bug report at http://bugzilla.wikimedia.org/'
476 * Override the parent to generate help messages for all available modules.
478 public function makeHelpMsg() {
480 $this->mPrinter->setHelp();
482 // Use parent to make default message for the main module
483 $msg = parent :: makeHelpMsg();
485 $astriks = str_repeat('*** ', 10);
486 $msg .= "\n\n$astriks Modules $astriks\n\n";
487 foreach( $this->mModules as $moduleName => $unused ) {
488 $module = new $this->mModules[$moduleName] ($this, $moduleName);
489 $msg .= self::makeHelpMsgHeader($module, 'action');
490 $msg2 = $module->makeHelpMsg();
491 if ($msg2 !== false)
492 $msg .= $msg2;
493 $msg .= "\n";
496 $msg .= "\n$astriks Formats $astriks\n\n";
497 foreach( $this->mFormats as $formatName => $unused ) {
498 $module = $this->createPrinterByName($formatName);
499 $msg .= self::makeHelpMsgHeader($module, 'format');
500 $msg2 = $module->makeHelpMsg();
501 if ($msg2 !== false)
502 $msg .= $msg2;
503 $msg .= "\n";
506 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
509 return $msg;
512 public static function makeHelpMsgHeader($module, $paramName) {
513 $modulePrefix = $module->getModulePrefix();
514 if (!empty($modulePrefix))
515 $modulePrefix = "($modulePrefix) ";
517 return "* $paramName={$module->getModuleName()} $modulePrefix*";
520 private $mIsBot = null;
521 private $mIsSysop = null;
522 private $mCanApiHighLimits = null;
525 * Returns true if the currently logged in user is a bot, false otherwise
526 * OBSOLETE, use canApiHighLimits() instead
528 public function isBot() {
529 if (!isset ($this->mIsBot)) {
530 global $wgUser;
531 $this->mIsBot = $wgUser->isAllowed('bot');
533 return $this->mIsBot;
537 * Similar to isBot(), this method returns true if the logged in user is
538 * a sysop, and false if not.
539 * OBSOLETE, use canApiHighLimits() instead
541 public function isSysop() {
542 if (!isset ($this->mIsSysop)) {
543 global $wgUser;
544 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
547 return $this->mIsSysop;
551 * Check whether the current user is allowed to use high limits
552 * @return bool
554 public function canApiHighLimits() {
555 if (!isset($this->mCanApiHighLimits)) {
556 global $wgUser;
557 $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
560 return $this->mCanApiHighLimits;
564 * Check whether the user wants us to show version information in the API help
565 * @return bool
567 public function getShowVersions() {
568 return $this->mShowVersions;
572 * Returns the version information of this file, plus it includes
573 * the versions for all files that are not callable proper API modules
575 public function getVersion() {
576 $vers = array ();
577 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
578 $vers[] = __CLASS__ . ': $Id$';
579 $vers[] = ApiBase :: getBaseVersion();
580 $vers[] = ApiFormatBase :: getBaseVersion();
581 $vers[] = ApiQueryBase :: getBaseVersion();
582 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
583 return $vers;
587 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
588 * classes who wish to add their own modules to their lexicon or override the
589 * behavior of inherent ones.
591 * @access protected
592 * @param $mdlName String The identifier for this module.
593 * @param $mdlClass String The class where this module is implemented.
595 protected function addModule( $mdlName, $mdlClass ) {
596 $this->mModules[$mdlName] = $mdlClass;
600 * Add or overwrite an output format for this ApiMain. Intended for use by extending
601 * classes who wish to add to or modify current formatters.
603 * @access protected
604 * @param $fmtName The identifier for this format.
605 * @param $fmtClass The class implementing this format.
607 protected function addFormat( $fmtName, $fmtClass ) {
608 $this->mFormats[$fmtName] = $fmtClass;
612 * Get the array mapping module names to class names
614 function getModules() {
615 return $this->mModules;
620 * This exception will be thrown when dieUsage is called to stop module execution.
621 * The exception handling code will print a help screen explaining how this API may be used.
623 * @ingroup API
625 class UsageException extends Exception {
627 private $mCodestr;
629 public function __construct($message, $codestr, $code = 0) {
630 parent :: __construct($message, $code);
631 $this->mCodestr = $codestr;
633 public function getCodeString() {
634 return $this->mCodestr;
636 public function __toString() {
637 return "{$this->getCodeString()}: {$this->getMessage()}";