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