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