ApiMain.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. <?php
  2. /*
  3. * Created on Sep 4, 2006
  4. *
  5. * API for MediaWiki 1.8+
  6. *
  7. * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. * http://www.gnu.org/copyleft/gpl.html
  23. */
  24. if (!defined('MEDIAWIKI')) {
  25. // Eclipse helper - will be ignored in production
  26. require_once ('ApiBase.php');
  27. }
  28. /**
  29. * @defgroup API API
  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. * @ingroup API
  43. */
  44. class ApiMain extends ApiBase {
  45. /**
  46. * When no format parameter is given, this format will be used
  47. */
  48. const API_DEFAULT_FORMAT = 'xmlfm';
  49. /**
  50. * List of available modules: action name => module class
  51. */
  52. private static $Modules = array (
  53. 'login' => 'ApiLogin',
  54. 'logout' => 'ApiLogout',
  55. 'query' => 'ApiQuery',
  56. 'expandtemplates' => 'ApiExpandTemplates',
  57. 'parse' => 'ApiParse',
  58. 'opensearch' => 'ApiOpenSearch',
  59. 'feedwatchlist' => 'ApiFeedWatchlist',
  60. 'help' => 'ApiHelp',
  61. 'paraminfo' => 'ApiParamInfo',
  62. // Write modules
  63. 'purge' => 'ApiPurge',
  64. 'rollback' => 'ApiRollback',
  65. 'delete' => 'ApiDelete',
  66. 'undelete' => 'ApiUndelete',
  67. 'protect' => 'ApiProtect',
  68. 'block' => 'ApiBlock',
  69. 'unblock' => 'ApiUnblock',
  70. 'move' => 'ApiMove',
  71. 'edit' => 'ApiEditPage',
  72. 'emailuser' => 'ApiEmailUser',
  73. 'watch' => 'ApiWatch',
  74. 'patrol' => 'ApiPatrol',
  75. 'import' => 'ApiImport',
  76. );
  77. /**
  78. * List of available formats: format name => format class
  79. */
  80. private static $Formats = array (
  81. 'json' => 'ApiFormatJson',
  82. 'jsonfm' => 'ApiFormatJson',
  83. 'php' => 'ApiFormatPhp',
  84. 'phpfm' => 'ApiFormatPhp',
  85. 'wddx' => 'ApiFormatWddx',
  86. 'wddxfm' => 'ApiFormatWddx',
  87. 'xml' => 'ApiFormatXml',
  88. 'xmlfm' => 'ApiFormatXml',
  89. 'yaml' => 'ApiFormatYaml',
  90. 'yamlfm' => 'ApiFormatYaml',
  91. 'rawfm' => 'ApiFormatJson',
  92. 'txt' => 'ApiFormatTxt',
  93. 'txtfm' => 'ApiFormatTxt',
  94. 'dbg' => 'ApiFormatDbg',
  95. 'dbgfm' => 'ApiFormatDbg'
  96. );
  97. /**
  98. * List of user roles that are specifically relevant to the API.
  99. * array( 'right' => array ( 'msg' => 'Some message with a $1',
  100. * 'params' => array ( $someVarToSubst ) ),
  101. * );
  102. */
  103. private static $mRights = array('writeapi' => array(
  104. 'msg' => 'Use of the write API',
  105. 'params' => array()
  106. ),
  107. 'apihighlimits' => array(
  108. 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
  109. 'params' => array (ApiMain::LIMIT_SML2, ApiMain::LIMIT_BIG2)
  110. )
  111. );
  112. private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
  113. private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
  114. /**
  115. * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
  116. *
  117. * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
  118. * @param $enableWrite bool should be set to true if the api may modify data
  119. */
  120. public function __construct($request, $enableWrite = false) {
  121. $this->mInternalMode = ($request instanceof FauxRequest);
  122. // Special handling for the main module: $parent === $this
  123. parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
  124. if (!$this->mInternalMode) {
  125. // Impose module restrictions.
  126. // If the current user cannot read,
  127. // Remove all modules other than login
  128. global $wgUser;
  129. if( $request->getVal( 'callback' ) !== null ) {
  130. // JSON callback allows cross-site reads.
  131. // For safety, strip user credentials.
  132. wfDebug( "API: stripping user credentials for JSON callback\n" );
  133. $wgUser = new User();
  134. }
  135. }
  136. global $wgAPIModules; // extension modules
  137. $this->mModules = $wgAPIModules + self :: $Modules;
  138. $this->mModuleNames = array_keys($this->mModules);
  139. $this->mFormats = self :: $Formats;
  140. $this->mFormatNames = array_keys($this->mFormats);
  141. $this->mResult = new ApiResult($this);
  142. $this->mShowVersions = false;
  143. $this->mEnableWrite = $enableWrite;
  144. $this->mRequest = & $request;
  145. $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
  146. $this->mCommit = false;
  147. }
  148. /**
  149. * Return true if the API was started by other PHP code using FauxRequest
  150. */
  151. public function isInternalMode() {
  152. return $this->mInternalMode;
  153. }
  154. /**
  155. * Return the request object that contains client's request
  156. */
  157. public function getRequest() {
  158. return $this->mRequest;
  159. }
  160. /**
  161. * Get the ApiResult object asscosiated with current request
  162. */
  163. public function getResult() {
  164. return $this->mResult;
  165. }
  166. /**
  167. * Only kept for backwards compatibility
  168. * @deprecated Use isWriteMode() instead
  169. */
  170. public function requestWriteMode() {}
  171. /**
  172. * Set how long the response should be cached.
  173. */
  174. public function setCacheMaxAge($maxage) {
  175. $this->mSquidMaxage = $maxage;
  176. }
  177. /**
  178. * Create an instance of an output formatter by its name
  179. */
  180. public function createPrinterByName($format) {
  181. if( !isset( $this->mFormats[$format] ) )
  182. $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
  183. return new $this->mFormats[$format] ($this, $format);
  184. }
  185. /**
  186. * Execute api request. Any errors will be handled if the API was called by the remote client.
  187. */
  188. public function execute() {
  189. $this->profileIn();
  190. if ($this->mInternalMode)
  191. $this->executeAction();
  192. else
  193. $this->executeActionWithErrorHandling();
  194. $this->profileOut();
  195. }
  196. /**
  197. * Execute an action, and in case of an error, erase whatever partial results
  198. * have been accumulated, and replace it with an error message and a help screen.
  199. */
  200. protected function executeActionWithErrorHandling() {
  201. // In case an error occurs during data output,
  202. // clear the output buffer and print just the error information
  203. ob_start();
  204. try {
  205. $this->executeAction();
  206. } catch (Exception $e) {
  207. // Log it
  208. if ( $e instanceof MWException ) {
  209. wfDebugLog( 'exception', $e->getLogMessage() );
  210. }
  211. //
  212. // Handle any kind of exception by outputing properly formatted error message.
  213. // If this fails, an unhandled exception should be thrown so that global error
  214. // handler will process and log it.
  215. //
  216. $errCode = $this->substituteResultWithError($e);
  217. // Error results should not be cached
  218. $this->setCacheMaxAge(0);
  219. $headerStr = 'MediaWiki-API-Error: ' . $errCode;
  220. if ($e->getCode() === 0)
  221. header($headerStr);
  222. else
  223. header($headerStr, true, $e->getCode());
  224. // Reset and print just the error message
  225. ob_clean();
  226. // If the error occured during printing, do a printer->profileOut()
  227. $this->mPrinter->safeProfileOut();
  228. $this->printResult(true);
  229. }
  230. if($this->mSquidMaxage == -1)
  231. {
  232. # Nobody called setCacheMaxAge(), use the (s)maxage parameters
  233. $smaxage = $this->getParameter('smaxage');
  234. $maxage = $this->getParameter('maxage');
  235. }
  236. else
  237. $smaxage = $maxage = $this->mSquidMaxage;
  238. // Set the cache expiration at the last moment, as any errors may change the expiration.
  239. // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
  240. $exp = min($smaxage, $maxage);
  241. $expires = ($exp == 0 ? 1 : time() + $exp);
  242. header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
  243. header('Cache-Control: s-maxage=' . $smaxage . ', must-revalidate, max-age=' . $maxage);
  244. if($this->mPrinter->getIsHtml())
  245. echo wfReportTime();
  246. ob_end_flush();
  247. }
  248. /**
  249. * Replace the result data with the information about an exception.
  250. * Returns the error code
  251. */
  252. protected function substituteResultWithError($e) {
  253. // Printer may not be initialized if the extractRequestParams() fails for the main module
  254. if (!isset ($this->mPrinter)) {
  255. // The printer has not been created yet. Try to manually get formatter value.
  256. $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
  257. if (!in_array($value, $this->mFormatNames))
  258. $value = self::API_DEFAULT_FORMAT;
  259. $this->mPrinter = $this->createPrinterByName($value);
  260. if ($this->mPrinter->getNeedsRawData())
  261. $this->getResult()->setRawMode();
  262. }
  263. if ($e instanceof UsageException) {
  264. //
  265. // User entered incorrect parameters - print usage screen
  266. //
  267. $errMessage = array (
  268. 'code' => $e->getCodeString(),
  269. 'info' => $e->getMessage());
  270. // Only print the help message when this is for the developer, not runtime
  271. if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
  272. ApiResult :: setContent($errMessage, $this->makeHelpMsg());
  273. } else {
  274. global $wgShowSQLErrors, $wgShowExceptionDetails;
  275. //
  276. // Something is seriously wrong
  277. //
  278. if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
  279. $info = "Database query error";
  280. } else {
  281. $info = "Exception Caught: {$e->getMessage()}";
  282. }
  283. $errMessage = array (
  284. 'code' => 'internal_api_error_'. get_class($e),
  285. 'info' => $info,
  286. );
  287. ApiResult :: setContent($errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : "" );
  288. }
  289. $this->getResult()->reset();
  290. $this->getResult()->disableSizeCheck();
  291. // Re-add the id
  292. $requestid = $this->getParameter('requestid');
  293. if(!is_null($requestid))
  294. $this->getResult()->addValue(null, 'requestid', $requestid);
  295. $this->getResult()->addValue(null, 'error', $errMessage);
  296. return $errMessage['code'];
  297. }
  298. /**
  299. * Execute the actual module, without any error handling
  300. */
  301. protected function executeAction() {
  302. // First add the id to the top element
  303. $requestid = $this->getParameter('requestid');
  304. if(!is_null($requestid))
  305. $this->getResult()->addValue(null, 'requestid', $requestid);
  306. $params = $this->extractRequestParams();
  307. $this->mShowVersions = $params['version'];
  308. $this->mAction = $params['action'];
  309. if( !is_string( $this->mAction ) ) {
  310. $this->dieUsage( "The API requires a valid action parameter", 'unknown_action' );
  311. }
  312. // Instantiate the module requested by the user
  313. $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
  314. if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
  315. // Check for maxlag
  316. global $wgShowHostnames;
  317. $maxLag = $params['maxlag'];
  318. list( $host, $lag ) = wfGetLB()->getMaxLag();
  319. if ( $lag > $maxLag ) {
  320. header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
  321. header( 'X-Database-Lag: ' . intval( $lag ) );
  322. // XXX: should we return a 503 HTTP error code like wfMaxlagError() does?
  323. if( $wgShowHostnames ) {
  324. $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
  325. } else {
  326. $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
  327. }
  328. return;
  329. }
  330. }
  331. global $wgUser;
  332. if ($module->isReadMode() && !$wgUser->isAllowed('read'))
  333. $this->dieUsageMsg(array('readrequired'));
  334. if ($module->isWriteMode()) {
  335. if (!$this->mEnableWrite)
  336. $this->dieUsageMsg(array('writedisabled'));
  337. if (!$wgUser->isAllowed('writeapi'))
  338. $this->dieUsageMsg(array('writerequired'));
  339. if (wfReadOnly())
  340. $this->dieUsageMsg(array('readonlytext'));
  341. }
  342. if (!$this->mInternalMode) {
  343. // Ignore mustBePosted() for internal calls
  344. if($module->mustBePosted() && !$this->mRequest->wasPosted())
  345. $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
  346. // See if custom printer is used
  347. $this->mPrinter = $module->getCustomPrinter();
  348. if (is_null($this->mPrinter)) {
  349. // Create an appropriate printer
  350. $this->mPrinter = $this->createPrinterByName($params['format']);
  351. }
  352. if ($this->mPrinter->getNeedsRawData())
  353. $this->getResult()->setRawMode();
  354. }
  355. // Execute
  356. $module->profileIn();
  357. $module->execute();
  358. wfRunHooks('APIAfterExecute', array(&$module));
  359. $module->profileOut();
  360. if (!$this->mInternalMode) {
  361. // Print result data
  362. $this->printResult(false);
  363. }
  364. }
  365. /**
  366. * Print results using the current printer
  367. */
  368. protected function printResult($isError) {
  369. $this->getResult()->cleanUpUTF8();
  370. $printer = $this->mPrinter;
  371. $printer->profileIn();
  372. /* If the help message is requested in the default (xmlfm) format,
  373. * tell the printer not to escape ampersands so that our links do
  374. * not break. */
  375. $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
  376. && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
  377. $printer->initPrinter($isError);
  378. $printer->execute();
  379. $printer->closePrinter();
  380. $printer->profileOut();
  381. }
  382. public function isReadMode() {
  383. return false;
  384. }
  385. /**
  386. * See ApiBase for description.
  387. */
  388. public function getAllowedParams() {
  389. return array (
  390. 'format' => array (
  391. ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
  392. ApiBase :: PARAM_TYPE => $this->mFormatNames
  393. ),
  394. 'action' => array (
  395. ApiBase :: PARAM_DFLT => 'help',
  396. ApiBase :: PARAM_TYPE => $this->mModuleNames
  397. ),
  398. 'version' => false,
  399. 'maxlag' => array (
  400. ApiBase :: PARAM_TYPE => 'integer'
  401. ),
  402. 'smaxage' => array (
  403. ApiBase :: PARAM_TYPE => 'integer',
  404. ApiBase :: PARAM_DFLT => 0
  405. ),
  406. 'maxage' => array (
  407. ApiBase :: PARAM_TYPE => 'integer',
  408. ApiBase :: PARAM_DFLT => 0
  409. ),
  410. 'requestid' => null,
  411. );
  412. }
  413. /**
  414. * See ApiBase for description.
  415. */
  416. public function getParamDescription() {
  417. return array (
  418. 'format' => 'The format of the output',
  419. 'action' => 'What action you would like to perform',
  420. 'version' => 'When showing help, include version for each module',
  421. 'maxlag' => 'Maximum lag',
  422. 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
  423. 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
  424. 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
  425. );
  426. }
  427. /**
  428. * See ApiBase for description.
  429. */
  430. public function getDescription() {
  431. return array (
  432. '',
  433. '',
  434. '******************************************************************',
  435. '** **',
  436. '** This is an auto-generated MediaWiki API documentation page **',
  437. '** **',
  438. '** Documentation and Examples: **',
  439. '** http://www.mediawiki.org/wiki/API **',
  440. '** **',
  441. '******************************************************************',
  442. '',
  443. 'Status: All features shown on this page should be working, but the API',
  444. ' is still in active development, and may change at any time.',
  445. ' Make sure to monitor our mailing list for any updates.',
  446. '',
  447. 'Documentation: http://www.mediawiki.org/wiki/API',
  448. 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
  449. 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
  450. '',
  451. '',
  452. '',
  453. '',
  454. '',
  455. );
  456. }
  457. /**
  458. * Returns an array of strings with credits for the API
  459. */
  460. protected function getCredits() {
  461. return array(
  462. 'API developers:',
  463. ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
  464. ' Victor Vasiliev - vasilvv at gee mail dot com',
  465. ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
  466. ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
  467. '',
  468. 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
  469. 'or file a bug report at http://bugzilla.wikimedia.org/'
  470. );
  471. }
  472. /**
  473. * Override the parent to generate help messages for all available modules.
  474. */
  475. public function makeHelpMsg() {
  476. $this->mPrinter->setHelp();
  477. // Use parent to make default message for the main module
  478. $msg = parent :: makeHelpMsg();
  479. $astriks = str_repeat('*** ', 10);
  480. $msg .= "\n\n$astriks Modules $astriks\n\n";
  481. foreach( $this->mModules as $moduleName => $unused ) {
  482. $module = new $this->mModules[$moduleName] ($this, $moduleName);
  483. $msg .= self::makeHelpMsgHeader($module, 'action');
  484. $msg2 = $module->makeHelpMsg();
  485. if ($msg2 !== false)
  486. $msg .= $msg2;
  487. $msg .= "\n";
  488. }
  489. $msg .= "\n$astriks Permissions $astriks\n\n";
  490. foreach ( self :: $mRights as $right => $rightMsg ) {
  491. $groups = User::getGroupsWithPermission( $right );
  492. $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
  493. "\nGranted to:\n " . str_replace( "*", "all", implode( ", ", $groups ) ) . "\n";
  494. }
  495. $msg .= "\n$astriks Formats $astriks\n\n";
  496. foreach( $this->mFormats as $formatName => $unused ) {
  497. $module = $this->createPrinterByName($formatName);
  498. $msg .= self::makeHelpMsgHeader($module, 'format');
  499. $msg2 = $module->makeHelpMsg();
  500. if ($msg2 !== false)
  501. $msg .= $msg2;
  502. $msg .= "\n";
  503. }
  504. $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
  505. return $msg;
  506. }
  507. public static function makeHelpMsgHeader($module, $paramName) {
  508. $modulePrefix = $module->getModulePrefix();
  509. if (strval($modulePrefix) !== '')
  510. $modulePrefix = "($modulePrefix) ";
  511. return "* $paramName={$module->getModuleName()} $modulePrefix*";
  512. }
  513. private $mIsBot = null;
  514. private $mIsSysop = null;
  515. private $mCanApiHighLimits = null;
  516. /**
  517. * Returns true if the currently logged in user is a bot, false otherwise
  518. * OBSOLETE, use canApiHighLimits() instead
  519. */
  520. public function isBot() {
  521. if (!isset ($this->mIsBot)) {
  522. global $wgUser;
  523. $this->mIsBot = $wgUser->isAllowed('bot');
  524. }
  525. return $this->mIsBot;
  526. }
  527. /**
  528. * Similar to isBot(), this method returns true if the logged in user is
  529. * a sysop, and false if not.
  530. * OBSOLETE, use canApiHighLimits() instead
  531. */
  532. public function isSysop() {
  533. if (!isset ($this->mIsSysop)) {
  534. global $wgUser;
  535. $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
  536. }
  537. return $this->mIsSysop;
  538. }
  539. /**
  540. * Check whether the current user is allowed to use high limits
  541. * @return bool
  542. */
  543. public function canApiHighLimits() {
  544. if (!isset($this->mCanApiHighLimits)) {
  545. global $wgUser;
  546. $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
  547. }
  548. return $this->mCanApiHighLimits;
  549. }
  550. /**
  551. * Check whether the user wants us to show version information in the API help
  552. * @return bool
  553. */
  554. public function getShowVersions() {
  555. return $this->mShowVersions;
  556. }
  557. /**
  558. * Returns the version information of this file, plus it includes
  559. * the versions for all files that are not callable proper API modules
  560. */
  561. public function getVersion() {
  562. $vers = array ();
  563. $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
  564. $vers[] = __CLASS__ . ': $Id: ApiMain.php 50834 2009-05-20 20:10:47Z catrope $';
  565. $vers[] = ApiBase :: getBaseVersion();
  566. $vers[] = ApiFormatBase :: getBaseVersion();
  567. $vers[] = ApiQueryBase :: getBaseVersion();
  568. $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
  569. return $vers;
  570. }
  571. /**
  572. * Add or overwrite a module in this ApiMain instance. Intended for use by extending
  573. * classes who wish to add their own modules to their lexicon or override the
  574. * behavior of inherent ones.
  575. *
  576. * @access protected
  577. * @param $mdlName String The identifier for this module.
  578. * @param $mdlClass String The class where this module is implemented.
  579. */
  580. protected function addModule( $mdlName, $mdlClass ) {
  581. $this->mModules[$mdlName] = $mdlClass;
  582. }
  583. /**
  584. * Add or overwrite an output format for this ApiMain. Intended for use by extending
  585. * classes who wish to add to or modify current formatters.
  586. *
  587. * @access protected
  588. * @param $fmtName The identifier for this format.
  589. * @param $fmtClass The class implementing this format.
  590. */
  591. protected function addFormat( $fmtName, $fmtClass ) {
  592. $this->mFormats[$fmtName] = $fmtClass;
  593. }
  594. /**
  595. * Get the array mapping module names to class names
  596. */
  597. function getModules() {
  598. return $this->mModules;
  599. }
  600. }
  601. /**
  602. * This exception will be thrown when dieUsage is called to stop module execution.
  603. * The exception handling code will print a help screen explaining how this API may be used.
  604. *
  605. * @ingroup API
  606. */
  607. class UsageException extends Exception {
  608. private $mCodestr;
  609. public function __construct($message, $codestr, $code = 0) {
  610. parent :: __construct($message, $code);
  611. $this->mCodestr = $codestr;
  612. }
  613. public function getCodeString() {
  614. return $this->mCodestr;
  615. }
  616. public function __toString() {
  617. return "{$this->getCodeString()}: {$this->getMessage()}";
  618. }
  619. }