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