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