7600066a23eda66918f71e341e534247d830dc4d
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 4, 2006
6 *
7 * Copyright © 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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @defgroup API API
26 */
27
28 /**
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
34 *
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
38 *
39 * @ingroup API
40 */
41 class ApiMain extends ApiBase {
42 /**
43 * When no format parameter is given, this format will be used
44 */
45 const API_DEFAULT_FORMAT = 'jsonfm';
46
47 /**
48 * List of available modules: action name => module class
49 */
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'opensearch' => 'ApiOpenSearch',
58 'feedcontributions' => 'ApiFeedContributions',
59 'feedrecentchanges' => 'ApiFeedRecentChanges',
60 'feedwatchlist' => 'ApiFeedWatchlist',
61 'help' => 'ApiHelp',
62 'paraminfo' => 'ApiParamInfo',
63 'rsd' => 'ApiRsd',
64 'compare' => 'ApiComparePages',
65 'tokens' => 'ApiTokens',
66
67 // Write modules
68 'purge' => 'ApiPurge',
69 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
70 'rollback' => 'ApiRollback',
71 'delete' => 'ApiDelete',
72 'undelete' => 'ApiUndelete',
73 'protect' => 'ApiProtect',
74 'block' => 'ApiBlock',
75 'unblock' => 'ApiUnblock',
76 'move' => 'ApiMove',
77 'edit' => 'ApiEditPage',
78 'upload' => 'ApiUpload',
79 'filerevert' => 'ApiFileRevert',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'clearhasmsg' => 'ApiClearHasMsg',
85 'userrights' => 'ApiUserrights',
86 'options' => 'ApiOptions',
87 'imagerotate' => 'ApiImageRotate',
88 'revisiondelete' => 'ApiRevisionDelete',
89 );
90
91 /**
92 * List of available formats: format name => format class
93 */
94 private static $Formats = array(
95 'json' => 'ApiFormatJson',
96 'jsonfm' => 'ApiFormatJson',
97 'php' => 'ApiFormatPhp',
98 'phpfm' => 'ApiFormatPhp',
99 'wddx' => 'ApiFormatWddx',
100 'wddxfm' => 'ApiFormatWddx',
101 'xml' => 'ApiFormatXml',
102 'xmlfm' => 'ApiFormatXml',
103 'yaml' => 'ApiFormatYaml',
104 'yamlfm' => 'ApiFormatYaml',
105 'rawfm' => 'ApiFormatJson',
106 'txt' => 'ApiFormatTxt',
107 'txtfm' => 'ApiFormatTxt',
108 'dbg' => 'ApiFormatDbg',
109 'dbgfm' => 'ApiFormatDbg',
110 'dump' => 'ApiFormatDump',
111 'dumpfm' => 'ApiFormatDump',
112 'none' => 'ApiFormatNone',
113 );
114
115 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
116 /**
117 * List of user roles that are specifically relevant to the API.
118 * array( 'right' => array ( 'msg' => 'Some message with a $1',
119 * 'params' => array ( $someVarToSubst ) ),
120 * );
121 */
122 private static $mRights = array(
123 'writeapi' => array(
124 'msg' => 'right-writeapi',
125 'params' => array()
126 ),
127 'apihighlimits' => array(
128 'msg' => 'api-help-right-apihighlimits',
129 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
130 )
131 );
132 // @codingStandardsIgnoreEnd
133
134 /**
135 * @var ApiFormatBase
136 */
137 private $mPrinter;
138
139 private $mModuleMgr, $mResult;
140 private $mAction;
141 private $mEnableWrite;
142 private $mInternalMode, $mSquidMaxage, $mModule;
143
144 private $mCacheMode = 'private';
145 private $mCacheControl = array();
146 private $mParamsUsed = array();
147
148 /**
149 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
150 *
151 * @param IContextSource|WebRequest $context If this is an instance of
152 * FauxRequest, errors are thrown and no printing occurs
153 * @param bool $enableWrite Should be set to true if the api may modify data
154 */
155 public function __construct( $context = null, $enableWrite = false ) {
156 if ( $context === null ) {
157 $context = RequestContext::getMain();
158 } elseif ( $context instanceof WebRequest ) {
159 // BC for pre-1.19
160 $request = $context;
161 $context = RequestContext::getMain();
162 }
163 // We set a derivative context so we can change stuff later
164 $this->setContext( new DerivativeContext( $context ) );
165
166 if ( isset( $request ) ) {
167 $this->getContext()->setRequest( $request );
168 }
169
170 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
171
172 // Special handling for the main module: $parent === $this
173 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
174
175 if ( !$this->mInternalMode ) {
176 // Impose module restrictions.
177 // If the current user cannot read,
178 // Remove all modules other than login
179 global $wgUser;
180
181 if ( $this->getVal( 'callback' ) !== null ) {
182 // JSON callback allows cross-site reads.
183 // For safety, strip user credentials.
184 wfDebug( "API: stripping user credentials for JSON callback\n" );
185 $wgUser = new User();
186 $this->getContext()->setUser( $wgUser );
187 }
188 }
189
190 $uselang = $this->getParameter( 'uselang' );
191 if ( $uselang === 'user' ) {
192 $uselang = $this->getUser()->getOption( 'language' );
193 $uselang = RequestContext::sanitizeLangCode( $uselang );
194 wfRunHooks( 'UserGetLanguageObject', array( $this->getUser(), &$uselang, $this ) );
195 } elseif ( $uselang === 'content' ) {
196 global $wgContLang;
197 $uselang = $wgContLang->getCode();
198 }
199 $code = RequestContext::sanitizeLangCode( $uselang );
200 $this->getContext()->setLanguage( $code );
201 if ( !$this->mInternalMode ) {
202 global $wgLang;
203 $wgLang = $this->getContext()->getLanguage();
204 RequestContext::getMain()->setLanguage( $wgLang );
205 }
206
207 $config = $this->getConfig();
208 $this->mModuleMgr = new ApiModuleManager( $this );
209 $this->mModuleMgr->addModules( self::$Modules, 'action' );
210 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
211 $this->mModuleMgr->addModules( self::$Formats, 'format' );
212 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
213
214 $this->mResult = new ApiResult( $this );
215 $this->mEnableWrite = $enableWrite;
216
217 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
218 $this->mCommit = false;
219 }
220
221 /**
222 * Return true if the API was started by other PHP code using FauxRequest
223 * @return bool
224 */
225 public function isInternalMode() {
226 return $this->mInternalMode;
227 }
228
229 /**
230 * Get the ApiResult object associated with current request
231 *
232 * @return ApiResult
233 */
234 public function getResult() {
235 return $this->mResult;
236 }
237
238 /**
239 * Get the API module object. Only works after executeAction()
240 *
241 * @return ApiBase
242 */
243 public function getModule() {
244 return $this->mModule;
245 }
246
247 /**
248 * Get the result formatter object. Only works after setupExecuteAction()
249 *
250 * @return ApiFormatBase
251 */
252 public function getPrinter() {
253 return $this->mPrinter;
254 }
255
256 /**
257 * Set how long the response should be cached.
258 *
259 * @param int $maxage
260 */
261 public function setCacheMaxAge( $maxage ) {
262 $this->setCacheControl( array(
263 'max-age' => $maxage,
264 's-maxage' => $maxage
265 ) );
266 }
267
268 /**
269 * Set the type of caching headers which will be sent.
270 *
271 * @param string $mode One of:
272 * - 'public': Cache this object in public caches, if the maxage or smaxage
273 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
274 * not provided by any of these means, the object will be private.
275 * - 'private': Cache this object only in private client-side caches.
276 * - 'anon-public-user-private': Make this object cacheable for logged-out
277 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
278 * set consistently for a given URL, it cannot be set differently depending on
279 * things like the contents of the database, or whether the user is logged in.
280 *
281 * If the wiki does not allow anonymous users to read it, the mode set here
282 * will be ignored, and private caching headers will always be sent. In other words,
283 * the "public" mode is equivalent to saying that the data sent is as public as a page
284 * view.
285 *
286 * For user-dependent data, the private mode should generally be used. The
287 * anon-public-user-private mode should only be used where there is a particularly
288 * good performance reason for caching the anonymous response, but where the
289 * response to logged-in users may differ, or may contain private data.
290 *
291 * If this function is never called, then the default will be the private mode.
292 */
293 public function setCacheMode( $mode ) {
294 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
295 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
296
297 // Ignore for forwards-compatibility
298 return;
299 }
300
301 if ( !User::isEveryoneAllowed( 'read' ) ) {
302 // Private wiki, only private headers
303 if ( $mode !== 'private' ) {
304 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
305
306 return;
307 }
308 }
309
310 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
311 // User language is used for i18n, so we don't want to publicly
312 // cache. Anons are ok, because if they have non-default language
313 // then there's an appropriate Vary header set by whatever set
314 // their non-default language.
315 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
316 "'anon-public-user-private' due to uselang=user\n" );
317 $mode = 'anon-public-user-private';
318 }
319
320 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
321 $this->mCacheMode = $mode;
322 }
323
324 /**
325 * Set directives (key/value pairs) for the Cache-Control header.
326 * Boolean values will be formatted as such, by including or omitting
327 * without an equals sign.
328 *
329 * Cache control values set here will only be used if the cache mode is not
330 * private, see setCacheMode().
331 *
332 * @param array $directives
333 */
334 public function setCacheControl( $directives ) {
335 $this->mCacheControl = $directives + $this->mCacheControl;
336 }
337
338 /**
339 * Create an instance of an output formatter by its name
340 *
341 * @param string $format
342 *
343 * @return ApiFormatBase
344 */
345 public function createPrinterByName( $format ) {
346 $printer = $this->mModuleMgr->getModule( $format, 'format' );
347 if ( $printer === null ) {
348 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
349 }
350
351 return $printer;
352 }
353
354 /**
355 * Execute api request. Any errors will be handled if the API was called by the remote client.
356 */
357 public function execute() {
358 $this->profileIn();
359 if ( $this->mInternalMode ) {
360 $this->executeAction();
361 } else {
362 $this->executeActionWithErrorHandling();
363 }
364
365 $this->profileOut();
366 }
367
368 /**
369 * Execute an action, and in case of an error, erase whatever partial results
370 * have been accumulated, and replace it with an error message and a help screen.
371 */
372 protected function executeActionWithErrorHandling() {
373 // Verify the CORS header before executing the action
374 if ( !$this->handleCORS() ) {
375 // handleCORS() has sent a 403, abort
376 return;
377 }
378
379 // Exit here if the request method was OPTIONS
380 // (assume there will be a followup GET or POST)
381 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
382 return;
383 }
384
385 // In case an error occurs during data output,
386 // clear the output buffer and print just the error information
387 ob_start();
388
389 $t = microtime( true );
390 try {
391 $this->executeAction();
392 } catch ( Exception $e ) {
393 $this->handleException( $e );
394 }
395
396 // Log the request whether or not there was an error
397 $this->logRequest( microtime( true ) - $t );
398
399 // Send cache headers after any code which might generate an error, to
400 // avoid sending public cache headers for errors.
401 $this->sendCacheHeaders();
402
403 ob_end_flush();
404 }
405
406 /**
407 * Handle an exception as an API response
408 *
409 * @since 1.23
410 * @param Exception $e
411 */
412 protected function handleException( Exception $e ) {
413 // Bug 63145: Rollback any open database transactions
414 if ( !( $e instanceof UsageException ) ) {
415 // UsageExceptions are intentional, so don't rollback if that's the case
416 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
417 }
418
419 // Allow extra cleanup and logging
420 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
421
422 // Log it
423 if ( !( $e instanceof UsageException ) ) {
424 MWExceptionHandler::logException( $e );
425 }
426
427 // Handle any kind of exception by outputting properly formatted error message.
428 // If this fails, an unhandled exception should be thrown so that global error
429 // handler will process and log it.
430
431 $errCode = $this->substituteResultWithError( $e );
432
433 // Error results should not be cached
434 $this->setCacheMode( 'private' );
435
436 $response = $this->getRequest()->response();
437 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
438 if ( $e->getCode() === 0 ) {
439 $response->header( $headerStr );
440 } else {
441 $response->header( $headerStr, true, $e->getCode() );
442 }
443
444 // Reset and print just the error message
445 ob_clean();
446
447 // If the error occurred during printing, do a printer->profileOut()
448 $this->mPrinter->safeProfileOut();
449 $this->printResult( true );
450 }
451
452 /**
453 * Handle an exception from the ApiBeforeMain hook.
454 *
455 * This tries to print the exception as an API response, to be more
456 * friendly to clients. If it fails, it will rethrow the exception.
457 *
458 * @since 1.23
459 * @param Exception $e
460 */
461 public static function handleApiBeforeMainException( Exception $e ) {
462 ob_start();
463
464 try {
465 $main = new self( RequestContext::getMain(), false );
466 $main->handleException( $e );
467 } catch ( Exception $e2 ) {
468 // Nope, even that didn't work. Punt.
469 throw $e;
470 }
471
472 // Log the request and reset cache headers
473 $main->logRequest( 0 );
474 $main->sendCacheHeaders();
475
476 ob_end_flush();
477 }
478
479 /**
480 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
481 *
482 * If no origin parameter is present, nothing happens.
483 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
484 * is set and false is returned.
485 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
486 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
487 * headers are set.
488 *
489 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
490 */
491 protected function handleCORS() {
492 $originParam = $this->getParameter( 'origin' ); // defaults to null
493 if ( $originParam === null ) {
494 // No origin parameter, nothing to do
495 return true;
496 }
497
498 $request = $this->getRequest();
499 $response = $request->response();
500 // Origin: header is a space-separated list of origins, check all of them
501 $originHeader = $request->getHeader( 'Origin' );
502 if ( $originHeader === false ) {
503 $origins = array();
504 } else {
505 $origins = explode( ' ', $originHeader );
506 }
507
508 if ( !in_array( $originParam, $origins ) ) {
509 // origin parameter set but incorrect
510 // Send a 403 response
511 $message = HttpStatus::getMessage( 403 );
512 $response->header( "HTTP/1.1 403 $message", true, 403 );
513 $response->header( 'Cache-Control: no-cache' );
514 echo "'origin' parameter does not match Origin header\n";
515
516 return false;
517 }
518
519 $config = $this->getConfig();
520 $matchOrigin = self::matchOrigin(
521 $originParam,
522 $config->get( 'CrossSiteAJAXdomains' ),
523 $config->get( 'CrossSiteAJAXdomainExceptions' )
524 );
525
526 if ( $matchOrigin ) {
527 $response->header( "Access-Control-Allow-Origin: $originParam" );
528 $response->header( 'Access-Control-Allow-Credentials: true' );
529 $response->header( 'Access-Control-Allow-Headers: Api-User-Agent' );
530 $this->getOutput()->addVaryHeader( 'Origin' );
531 }
532
533 return true;
534 }
535
536 /**
537 * Attempt to match an Origin header against a set of rules and a set of exceptions
538 * @param string $value Origin header
539 * @param array $rules Set of wildcard rules
540 * @param array $exceptions Set of wildcard rules
541 * @return bool True if $value matches a rule in $rules and doesn't match
542 * any rules in $exceptions, false otherwise
543 */
544 protected static function matchOrigin( $value, $rules, $exceptions ) {
545 foreach ( $rules as $rule ) {
546 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
547 // Rule matches, check exceptions
548 foreach ( $exceptions as $exc ) {
549 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
550 return false;
551 }
552 }
553
554 return true;
555 }
556 }
557
558 return false;
559 }
560
561 /**
562 * Helper function to convert wildcard string into a regex
563 * '*' => '.*?'
564 * '?' => '.'
565 *
566 * @param string $wildcard String with wildcards
567 * @return string Regular expression
568 */
569 protected static function wildcardToRegex( $wildcard ) {
570 $wildcard = preg_quote( $wildcard, '/' );
571 $wildcard = str_replace(
572 array( '\*', '\?' ),
573 array( '.*?', '.' ),
574 $wildcard
575 );
576
577 return "/https?:\/\/$wildcard/";
578 }
579
580 protected function sendCacheHeaders() {
581 $response = $this->getRequest()->response();
582 $out = $this->getOutput();
583
584 $config = $this->getConfig();
585
586 if ( $config->get( 'VaryOnXFP' ) ) {
587 $out->addVaryHeader( 'X-Forwarded-Proto' );
588 }
589
590 if ( $this->mCacheMode == 'private' ) {
591 $response->header( 'Cache-Control: private' );
592 return;
593 }
594
595 $useXVO = $config->get( 'UseXVO' );
596 if ( $this->mCacheMode == 'anon-public-user-private' ) {
597 $out->addVaryHeader( 'Cookie' );
598 $response->header( $out->getVaryHeader() );
599 if ( $useXVO ) {
600 $response->header( $out->getXVO() );
601 if ( $out->haveCacheVaryCookies() ) {
602 // Logged in, mark this request private
603 $response->header( 'Cache-Control: private' );
604 return;
605 }
606 // Logged out, send normal public headers below
607 } elseif ( session_id() != '' ) {
608 // Logged in or otherwise has session (e.g. anonymous users who have edited)
609 // Mark request private
610 $response->header( 'Cache-Control: private' );
611
612 return;
613 } // else no XVO and anonymous, send public headers below
614 }
615
616 // Send public headers
617 $response->header( $out->getVaryHeader() );
618 if ( $useXVO ) {
619 $response->header( $out->getXVO() );
620 }
621
622 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
623 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
624 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
625 }
626 if ( !isset( $this->mCacheControl['max-age'] ) ) {
627 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
628 }
629
630 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
631 // Public cache not requested
632 // Sending a Vary header in this case is harmless, and protects us
633 // against conditional calls of setCacheMaxAge().
634 $response->header( 'Cache-Control: private' );
635
636 return;
637 }
638
639 $this->mCacheControl['public'] = true;
640
641 // Send an Expires header
642 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
643 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
644 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
645
646 // Construct the Cache-Control header
647 $ccHeader = '';
648 $separator = '';
649 foreach ( $this->mCacheControl as $name => $value ) {
650 if ( is_bool( $value ) ) {
651 if ( $value ) {
652 $ccHeader .= $separator . $name;
653 $separator = ', ';
654 }
655 } else {
656 $ccHeader .= $separator . "$name=$value";
657 $separator = ', ';
658 }
659 }
660
661 $response->header( "Cache-Control: $ccHeader" );
662 }
663
664 /**
665 * Replace the result data with the information about an exception.
666 * Returns the error code
667 * @param Exception $e
668 * @return string
669 */
670 protected function substituteResultWithError( $e ) {
671 $result = $this->getResult();
672
673 // Printer may not be initialized if the extractRequestParams() fails for the main module
674 if ( !isset( $this->mPrinter ) ) {
675 // The printer has not been created yet. Try to manually get formatter value.
676 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
677 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
678 $value = self::API_DEFAULT_FORMAT;
679 }
680
681 $this->mPrinter = $this->createPrinterByName( $value );
682 }
683
684 // Printer may not be able to handle errors. This is particularly
685 // likely if the module returns something for getCustomPrinter().
686 if ( !$this->mPrinter->canPrintErrors() ) {
687 $this->mPrinter->safeProfileOut();
688 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
689 }
690
691 // Update raw mode flag for the selected printer.
692 $result->setRawMode( $this->mPrinter->getNeedsRawData() );
693
694 $config = $this->getConfig();
695
696 if ( $e instanceof UsageException ) {
697 // User entered incorrect parameters - generate error response
698 $errMessage = $e->getMessageArray();
699 $link = wfExpandUrl( wfScript( 'api' ) );
700 ApiResult::setContent( $errMessage, "See $link for API usage" );
701 } else {
702 // Something is seriously wrong
703 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
704 $info = 'Database query error';
705 } else {
706 $info = "Exception Caught: {$e->getMessage()}";
707 }
708
709 $errMessage = array(
710 'code' => 'internal_api_error_' . get_class( $e ),
711 'info' => $info,
712 );
713 ApiResult::setContent(
714 $errMessage,
715 $config->get( 'ShowExceptionDetails' ) ? "\n\n{$e->getTraceAsString()}\n\n" : ''
716 );
717 }
718
719 // Remember all the warnings to re-add them later
720 $oldResult = $result->getData();
721 $warnings = isset( $oldResult['warnings'] ) ? $oldResult['warnings'] : null;
722
723 $result->reset();
724 // Re-add the id
725 $requestid = $this->getParameter( 'requestid' );
726 if ( !is_null( $requestid ) ) {
727 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
728 }
729 if ( $config->get( 'ShowHostnames' ) ) {
730 // servedby is especially useful when debugging errors
731 $result->addValue( null, 'servedby', wfHostName(), ApiResult::NO_SIZE_CHECK );
732 }
733 if ( $warnings !== null ) {
734 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
735 }
736
737 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
738
739 return $errMessage['code'];
740 }
741
742 /**
743 * Set up for the execution.
744 * @return array
745 */
746 protected function setupExecuteAction() {
747 // First add the id to the top element
748 $result = $this->getResult();
749 $requestid = $this->getParameter( 'requestid' );
750 if ( !is_null( $requestid ) ) {
751 $result->addValue( null, 'requestid', $requestid );
752 }
753
754 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
755 $servedby = $this->getParameter( 'servedby' );
756 if ( $servedby ) {
757 $result->addValue( null, 'servedby', wfHostName() );
758 }
759 }
760
761 if ( $this->getParameter( 'curtimestamp' ) ) {
762 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
763 ApiResult::NO_SIZE_CHECK );
764 }
765
766 $params = $this->extractRequestParams();
767
768 $this->mAction = $params['action'];
769
770 if ( !is_string( $this->mAction ) ) {
771 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
772 }
773
774 return $params;
775 }
776
777 /**
778 * Set up the module for response
779 * @return ApiBase The module that will handle this action
780 */
781 protected function setupModule() {
782 // Instantiate the module requested by the user
783 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
784 if ( $module === null ) {
785 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
786 }
787 $moduleParams = $module->extractRequestParams();
788
789 // Check token, if necessary
790 if ( $module->needsToken() === true ) {
791 throw new MWException(
792 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
793 "See documentation for ApiBase::needsToken for details."
794 );
795 }
796 if ( $module->needsToken() ) {
797 if ( !$module->mustBePosted() ) {
798 throw new MWException(
799 "Module '{$module->getModuleName()}' must require POST to use tokens."
800 );
801 }
802
803 if ( !isset( $moduleParams['token'] ) ) {
804 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
805 }
806
807 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
808 array_key_exists(
809 $module->encodeParamName( 'token' ),
810 $this->getRequest()->getQueryValues()
811 )
812 ) {
813 $this->dieUsage(
814 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
815 'mustposttoken'
816 );
817 }
818
819 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
820 $this->dieUsageMsg( 'sessionfailure' );
821 }
822 }
823
824 return $module;
825 }
826
827 /**
828 * Check the max lag if necessary
829 * @param ApiBase $module Api module being used
830 * @param array $params Array an array containing the request parameters.
831 * @return bool True on success, false should exit immediately
832 */
833 protected function checkMaxLag( $module, $params ) {
834 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
835 // Check for maxlag
836 $maxLag = $params['maxlag'];
837 list( $host, $lag ) = wfGetLB()->getMaxLag();
838 if ( $lag > $maxLag ) {
839 $response = $this->getRequest()->response();
840
841 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
842 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
843
844 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
845 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
846 }
847
848 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
849 }
850 }
851
852 return true;
853 }
854
855 /**
856 * Check for sufficient permissions to execute
857 * @param ApiBase $module An Api module
858 */
859 protected function checkExecutePermissions( $module ) {
860 $user = $this->getUser();
861 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
862 !$user->isAllowed( 'read' )
863 ) {
864 $this->dieUsageMsg( 'readrequired' );
865 }
866 if ( $module->isWriteMode() ) {
867 if ( !$this->mEnableWrite ) {
868 $this->dieUsageMsg( 'writedisabled' );
869 }
870 if ( !$user->isAllowed( 'writeapi' ) ) {
871 $this->dieUsageMsg( 'writerequired' );
872 }
873 if ( wfReadOnly() ) {
874 $this->dieReadOnly();
875 }
876 }
877
878 // Allow extensions to stop execution for arbitrary reasons.
879 $message = false;
880 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
881 $this->dieUsageMsg( $message );
882 }
883 }
884
885 /**
886 * Check asserts of the user's rights
887 * @param array $params
888 */
889 protected function checkAsserts( $params ) {
890 if ( isset( $params['assert'] ) ) {
891 $user = $this->getUser();
892 switch ( $params['assert'] ) {
893 case 'user':
894 if ( $user->isAnon() ) {
895 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
896 }
897 break;
898 case 'bot':
899 if ( !$user->isAllowed( 'bot' ) ) {
900 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
901 }
902 break;
903 }
904 }
905 }
906
907 /**
908 * Check POST for external response and setup result printer
909 * @param ApiBase $module An Api module
910 * @param array $params An array with the request parameters
911 */
912 protected function setupExternalResponse( $module, $params ) {
913 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
914 // Module requires POST. GET request might still be allowed
915 // if $wgDebugApi is true, otherwise fail.
916 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
917 }
918
919 // See if custom printer is used
920 $this->mPrinter = $module->getCustomPrinter();
921 if ( is_null( $this->mPrinter ) ) {
922 // Create an appropriate printer
923 $this->mPrinter = $this->createPrinterByName( $params['format'] );
924 }
925
926 if ( $this->mPrinter->getNeedsRawData() ) {
927 $this->getResult()->setRawMode();
928 }
929 }
930
931 /**
932 * Execute the actual module, without any error handling
933 */
934 protected function executeAction() {
935 $params = $this->setupExecuteAction();
936 $module = $this->setupModule();
937 $this->mModule = $module;
938
939 $this->checkExecutePermissions( $module );
940
941 if ( !$this->checkMaxLag( $module, $params ) ) {
942 return;
943 }
944
945 if ( !$this->mInternalMode ) {
946 $this->setupExternalResponse( $module, $params );
947 }
948
949 $this->checkAsserts( $params );
950
951 // Execute
952 $module->profileIn();
953 $module->execute();
954 wfRunHooks( 'APIAfterExecute', array( &$module ) );
955 $module->profileOut();
956
957 $this->reportUnusedParams();
958
959 if ( !$this->mInternalMode ) {
960 //append Debug information
961 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
962
963 // Print result data
964 $this->printResult( false );
965 }
966 }
967
968 /**
969 * Log the preceding request
970 * @param int $time Time in seconds
971 */
972 protected function logRequest( $time ) {
973 $request = $this->getRequest();
974 $milliseconds = $time === null ? '?' : round( $time * 1000 );
975 $s = 'API' .
976 ' ' . $request->getMethod() .
977 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
978 ' ' . $request->getIP() .
979 ' T=' . $milliseconds . 'ms';
980 foreach ( $this->getParamsUsed() as $name ) {
981 $value = $request->getVal( $name );
982 if ( $value === null ) {
983 continue;
984 }
985 $s .= ' ' . $name . '=';
986 if ( strlen( $value ) > 256 ) {
987 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
988 $s .= $encValue . '[...]';
989 } else {
990 $s .= $this->encodeRequestLogValue( $value );
991 }
992 }
993 $s .= "\n";
994 wfDebugLog( 'api', $s, 'private' );
995 }
996
997 /**
998 * Encode a value in a format suitable for a space-separated log line.
999 * @param string $s
1000 * @return string
1001 */
1002 protected function encodeRequestLogValue( $s ) {
1003 static $table;
1004 if ( !$table ) {
1005 $chars = ';@$!*(),/:';
1006 $numChars = strlen( $chars );
1007 for ( $i = 0; $i < $numChars; $i++ ) {
1008 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1009 }
1010 }
1011
1012 return strtr( rawurlencode( $s ), $table );
1013 }
1014
1015 /**
1016 * Get the request parameters used in the course of the preceding execute() request
1017 * @return array
1018 */
1019 protected function getParamsUsed() {
1020 return array_keys( $this->mParamsUsed );
1021 }
1022
1023 /**
1024 * Get a request value, and register the fact that it was used, for logging.
1025 * @param string $name
1026 * @param mixed $default
1027 * @return mixed
1028 */
1029 public function getVal( $name, $default = null ) {
1030 $this->mParamsUsed[$name] = true;
1031
1032 $ret = $this->getRequest()->getVal( $name );
1033 if ( $ret === null ) {
1034 if ( $this->getRequest()->getArray( $name ) !== null ) {
1035 // See bug 10262 for why we don't just join( '|', ... ) the
1036 // array.
1037 $this->setWarning(
1038 "Parameter '$name' uses unsupported PHP array syntax"
1039 );
1040 }
1041 $ret = $default;
1042 }
1043 return $ret;
1044 }
1045
1046 /**
1047 * Get a boolean request value, and register the fact that the parameter
1048 * was used, for logging.
1049 * @param string $name
1050 * @return bool
1051 */
1052 public function getCheck( $name ) {
1053 return $this->getVal( $name, null ) !== null;
1054 }
1055
1056 /**
1057 * Get a request upload, and register the fact that it was used, for logging.
1058 *
1059 * @since 1.21
1060 * @param string $name Parameter name
1061 * @return WebRequestUpload
1062 */
1063 public function getUpload( $name ) {
1064 $this->mParamsUsed[$name] = true;
1065
1066 return $this->getRequest()->getUpload( $name );
1067 }
1068
1069 /**
1070 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1071 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1072 */
1073 protected function reportUnusedParams() {
1074 $paramsUsed = $this->getParamsUsed();
1075 $allParams = $this->getRequest()->getValueNames();
1076
1077 if ( !$this->mInternalMode ) {
1078 // Printer has not yet executed; don't warn that its parameters are unused
1079 $printerParams = array_map(
1080 array( $this->mPrinter, 'encodeParamName' ),
1081 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1082 );
1083 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1084 } else {
1085 $unusedParams = array_diff( $allParams, $paramsUsed );
1086 }
1087
1088 if ( count( $unusedParams ) ) {
1089 $s = count( $unusedParams ) > 1 ? 's' : '';
1090 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1091 }
1092 }
1093
1094 /**
1095 * Print results using the current printer
1096 *
1097 * @param bool $isError
1098 */
1099 protected function printResult( $isError ) {
1100 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1101 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1102 }
1103
1104 $this->getResult()->cleanUpUTF8();
1105 $printer = $this->mPrinter;
1106 $printer->profileIn();
1107
1108 $printer->initPrinter( false );
1109
1110 $printer->execute();
1111 $printer->closePrinter();
1112 $printer->profileOut();
1113 }
1114
1115 /**
1116 * @return bool
1117 */
1118 public function isReadMode() {
1119 return false;
1120 }
1121
1122 /**
1123 * See ApiBase for description.
1124 *
1125 * @return array
1126 */
1127 public function getAllowedParams() {
1128 return array(
1129 'action' => array(
1130 ApiBase::PARAM_DFLT => 'help',
1131 ApiBase::PARAM_TYPE => 'submodule',
1132 ),
1133 'format' => array(
1134 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1135 ApiBase::PARAM_TYPE => 'submodule',
1136 ),
1137 'maxlag' => array(
1138 ApiBase::PARAM_TYPE => 'integer'
1139 ),
1140 'smaxage' => array(
1141 ApiBase::PARAM_TYPE => 'integer',
1142 ApiBase::PARAM_DFLT => 0
1143 ),
1144 'maxage' => array(
1145 ApiBase::PARAM_TYPE => 'integer',
1146 ApiBase::PARAM_DFLT => 0
1147 ),
1148 'assert' => array(
1149 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1150 ),
1151 'requestid' => null,
1152 'servedby' => false,
1153 'curtimestamp' => false,
1154 'origin' => null,
1155 'uselang' => array(
1156 ApiBase::PARAM_DFLT => 'user',
1157 ),
1158 );
1159 }
1160
1161 /** @see ApiBase::getExamplesMessages() */
1162 protected function getExamplesMessages() {
1163 return array(
1164 'action=help'
1165 => 'apihelp-help-example-main',
1166 'action=help&recursivesubmodules=1'
1167 => 'apihelp-help-example-recursive',
1168 );
1169 }
1170
1171 public function modifyHelp( array &$help, array $options ) {
1172 // Wish PHP had an "array_insert_before". Instead, we have to manually
1173 // reindex the array to get 'permissions' in the right place.
1174 $oldHelp = $help;
1175 $help = array();
1176 foreach ( $oldHelp as $k => $v ) {
1177 if ( $k === 'submodules' ) {
1178 $help['permissions'] = '';
1179 }
1180 $help[$k] = $v;
1181 }
1182 $help['credits'] = '';
1183
1184 // Fill 'permissions'
1185 $help['permissions'] .= Html::openElement( 'div',
1186 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1187 $m = $this->msg( 'api-help-permissions' );
1188 if ( !$m->isDisabled() ) {
1189 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1190 $m->numParams( count( self::$mRights ) )->parse()
1191 );
1192 }
1193 $help['permissions'] .= Html::openElement( 'dl' );
1194 foreach ( self::$mRights as $right => $rightMsg ) {
1195 $help['permissions'] .= Html::element( 'dt', null, $right );
1196
1197 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1198 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1199
1200 $groups = array_map( function ( $group ) {
1201 return $group == '*' ? 'all' : $group;
1202 }, User::getGroupsWithPermission( $right ) );
1203
1204 $help['permissions'] .= Html::rawElement( 'dd', null,
1205 $this->msg( 'api-help-permissions-granted-to' )
1206 ->numParams( count( $groups ) )
1207 ->params( $this->getLanguage()->commaList( $groups ) )
1208 ->parse()
1209 );
1210 }
1211 $help['permissions'] .= Html::closeElement( 'dl' );
1212 $help['permissions'] .= Html::closeElement( 'div' );
1213
1214 // Fill 'credits', if applicable
1215 if ( empty( $options['nolead'] ) ) {
1216 $help['credits'] .= Html::element( 'h' . min( 6, $options['headerlevel'] + 1 ),
1217 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1218 $this->msg( 'api-credits-header' )->parse()
1219 );
1220 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1221 }
1222 }
1223
1224 private $mCanApiHighLimits = null;
1225
1226 /**
1227 * Check whether the current user is allowed to use high limits
1228 * @return bool
1229 */
1230 public function canApiHighLimits() {
1231 if ( !isset( $this->mCanApiHighLimits ) ) {
1232 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1233 }
1234
1235 return $this->mCanApiHighLimits;
1236 }
1237
1238 /**
1239 * Overrides to return this instance's module manager.
1240 * @return ApiModuleManager
1241 */
1242 public function getModuleManager() {
1243 return $this->mModuleMgr;
1244 }
1245
1246 /**
1247 * Fetches the user agent used for this request
1248 *
1249 * The value will be the combination of the 'Api-User-Agent' header (if
1250 * any) and the standard User-Agent header (if any).
1251 *
1252 * @return string
1253 */
1254 public function getUserAgent() {
1255 return trim(
1256 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1257 $this->getRequest()->getHeader( 'User-agent' )
1258 );
1259 }
1260
1261 /************************************************************************//**
1262 * @name Deprecated
1263 * @{
1264 */
1265
1266 /**
1267 * Sets whether the pretty-printer should format *bold* and $italics$
1268 *
1269 * @deprecated since 1.25
1270 * @param bool $help
1271 */
1272 public function setHelp( $help = true ) {
1273 wfDeprecated( __METHOD__, '1.25' );
1274 $this->mPrinter->setHelp( $help );
1275 }
1276
1277 /**
1278 * Override the parent to generate help messages for all available modules.
1279 *
1280 * @deprecated since 1.25
1281 * @return string
1282 */
1283 public function makeHelpMsg() {
1284 wfDeprecated( __METHOD__, '1.25' );
1285 global $wgMemc;
1286 $this->setHelp();
1287 // Get help text from cache if present
1288 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1289 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1290
1291 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1292 if ( $cacheHelpTimeout > 0 ) {
1293 $cached = $wgMemc->get( $key );
1294 if ( $cached ) {
1295 return $cached;
1296 }
1297 }
1298 $retval = $this->reallyMakeHelpMsg();
1299 if ( $cacheHelpTimeout > 0 ) {
1300 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1301 }
1302
1303 return $retval;
1304 }
1305
1306 /**
1307 * @deprecated since 1.25
1308 * @return mixed|string
1309 */
1310 public function reallyMakeHelpMsg() {
1311 wfDeprecated( __METHOD__, '1.25' );
1312 $this->setHelp();
1313
1314 // Use parent to make default message for the main module
1315 $msg = parent::makeHelpMsg();
1316
1317 $astriks = str_repeat( '*** ', 14 );
1318 $msg .= "\n\n$astriks Modules $astriks\n\n";
1319
1320 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1321 $module = $this->mModuleMgr->getModule( $name );
1322 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1323
1324 $msg2 = $module->makeHelpMsg();
1325 if ( $msg2 !== false ) {
1326 $msg .= $msg2;
1327 }
1328 $msg .= "\n";
1329 }
1330
1331 $msg .= "\n$astriks Permissions $astriks\n\n";
1332 foreach ( self::$mRights as $right => $rightMsg ) {
1333 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1334 ->useDatabase( false )
1335 ->inLanguage( 'en' )
1336 ->text();
1337 $groups = User::getGroupsWithPermission( $right );
1338 $msg .= "* " . $right . " *\n $rightsMsg" .
1339 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1340 }
1341
1342 $msg .= "\n$astriks Formats $astriks\n\n";
1343 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1344 $module = $this->mModuleMgr->getModule( $name );
1345 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1346 $msg2 = $module->makeHelpMsg();
1347 if ( $msg2 !== false ) {
1348 $msg .= $msg2;
1349 }
1350 $msg .= "\n";
1351 }
1352
1353 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1354 $credits = str_replace( "\n", "\n ", $credits );
1355 $msg .= "\n*** Credits: ***\n $credits\n";
1356
1357 return $msg;
1358 }
1359
1360 /**
1361 * @deprecated since 1.25
1362 * @param ApiBase $module
1363 * @param string $paramName What type of request is this? e.g. action,
1364 * query, list, prop, meta, format
1365 * @return string
1366 */
1367 public static function makeHelpMsgHeader( $module, $paramName ) {
1368 wfDeprecated( __METHOD__, '1.25' );
1369 $modulePrefix = $module->getModulePrefix();
1370 if ( strval( $modulePrefix ) !== '' ) {
1371 $modulePrefix = "($modulePrefix) ";
1372 }
1373
1374 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1375 }
1376
1377 /**
1378 * Check whether the user wants us to show version information in the API help
1379 * @return bool
1380 * @deprecated since 1.21, always returns false
1381 */
1382 public function getShowVersions() {
1383 wfDeprecated( __METHOD__, '1.21' );
1384
1385 return false;
1386 }
1387
1388 /**
1389 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1390 * classes who wish to add their own modules to their lexicon or override the
1391 * behavior of inherent ones.
1392 *
1393 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1394 * @param string $name The identifier for this module.
1395 * @param ApiBase $class The class where this module is implemented.
1396 */
1397 protected function addModule( $name, $class ) {
1398 $this->getModuleManager()->addModule( $name, 'action', $class );
1399 }
1400
1401 /**
1402 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1403 * classes who wish to add to or modify current formatters.
1404 *
1405 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1406 * @param string $name The identifier for this format.
1407 * @param ApiFormatBase $class The class implementing this format.
1408 */
1409 protected function addFormat( $name, $class ) {
1410 $this->getModuleManager()->addModule( $name, 'format', $class );
1411 }
1412
1413 /**
1414 * Get the array mapping module names to class names
1415 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1416 * @return array
1417 */
1418 function getModules() {
1419 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1420 }
1421
1422 /**
1423 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1424 *
1425 * @since 1.18
1426 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1427 * @return array
1428 */
1429 public function getFormats() {
1430 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1431 }
1432
1433 /**@}*/
1434
1435 }
1436
1437 /**
1438 * This exception will be thrown when dieUsage is called to stop module execution.
1439 *
1440 * @ingroup API
1441 */
1442 class UsageException extends MWException {
1443
1444 private $mCodestr;
1445
1446 /**
1447 * @var null|array
1448 */
1449 private $mExtraData;
1450
1451 /**
1452 * @param string $message
1453 * @param string $codestr
1454 * @param int $code
1455 * @param array|null $extradata
1456 */
1457 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1458 parent::__construct( $message, $code );
1459 $this->mCodestr = $codestr;
1460 $this->mExtraData = $extradata;
1461 }
1462
1463 /**
1464 * @return string
1465 */
1466 public function getCodeString() {
1467 return $this->mCodestr;
1468 }
1469
1470 /**
1471 * @return array
1472 */
1473 public function getMessageArray() {
1474 $result = array(
1475 'code' => $this->mCodestr,
1476 'info' => $this->getMessage()
1477 );
1478 if ( is_array( $this->mExtraData ) ) {
1479 $result = array_merge( $result, $this->mExtraData );
1480 }
1481
1482 return $result;
1483 }
1484
1485 /**
1486 * @return string
1487 */
1488 public function __toString() {
1489 return "{$this->getCodeString()}: {$this->getMessage()}";
1490 }
1491 }
1492
1493 /**
1494 * For really cool vim folding this needs to be at the end:
1495 * vim: foldmarker=@{,@} foldmethod=marker
1496 */