3 * This file contains the ApiErrorFormatter definition, plus implementations of
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
25 * Formats errors and warnings for the API, and add them to the associated
30 class ApiErrorFormatter
{
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
39 protected $useDB = false;
40 protected $format = 'none';
43 * @param ApiResult $result Into which data will be added
44 * @param Language $lang Used for i18n
45 * @param string $format
46 * - plaintext: Error message as something vaguely like plaintext
47 * (it's basically wikitext with HTML tags stripped and entities decoded)
48 * - wikitext: Error message as wikitext
49 * - html: Error message as HTML
50 * - raw: Raw message key and parameters, no human-readable text
51 * - none: Code and data only, no human-readable text
52 * @param bool $useDB Whether to use local translations for errors and warnings.
54 public function __construct( ApiResult
$result, Language
$lang, $format, $useDB = false ) {
55 $this->result
= $result;
57 $this->useDB
= $useDB;
58 $this->format
= $format;
62 * Test whether a code is a valid API error code
64 * A valid code contains only ASCII letters, numbers, underscore, and
65 * hyphen and is not the empty string.
67 * For backwards compatibility, any code beginning 'internal_api_error_' is
73 public static function isValidApiCode( $code ) {
74 return is_string( $code ) && (
75 preg_match( '/^[a-zA-Z0-9_-]+$/', $code ) ||
76 // TODO: Deprecate this
77 preg_match( '/^internal_api_error_[^\0\r\n]+$/', $code )
82 * Return a formatter like this one but with a different format
85 * @param string $format New format.
86 * @return ApiErrorFormatter
88 public function newWithFormat( $format ) {
89 return new self( $this->result
, $this->lang
, $format, $this->useDB
);
93 * Fetch the format for this formatter
97 public function getFormat() {
102 * Fetch the Language for this formatter
106 public function getLanguage() {
111 * Fetch a dummy title to set on Messages
114 protected function getDummyTitle() {
115 if ( self
::$dummyTitle === null ) {
116 self
::$dummyTitle = Title
::makeTitle( NS_SPECIAL
, 'Badtitle/' . __METHOD__
);
118 return self
::$dummyTitle;
122 * Add a warning to the result
123 * @param string|null $modulePath
124 * @param Message|array|string $msg Warning message. See ApiMessage::create().
125 * @param string|null $code See ApiMessage::create().
126 * @param array|null $data See ApiMessage::create().
128 public function addWarning( $modulePath, $msg, $code = null, $data = null ) {
129 $msg = ApiMessage
::create( $msg, $code, $data )
130 ->inLanguage( $this->lang
)
131 ->title( $this->getDummyTitle() )
132 ->useDatabase( $this->useDB
);
133 $this->addWarningOrError( 'warning', $modulePath, $msg );
137 * Add an error to the result
138 * @param string|null $modulePath
139 * @param Message|array|string $msg Warning message. See ApiMessage::create().
140 * @param string|null $code See ApiMessage::create().
141 * @param array|null $data See ApiMessage::create().
143 public function addError( $modulePath, $msg, $code = null, $data = null ) {
144 $msg = ApiMessage
::create( $msg, $code, $data )
145 ->inLanguage( $this->lang
)
146 ->title( $this->getDummyTitle() )
147 ->useDatabase( $this->useDB
);
148 $this->addWarningOrError( 'error', $modulePath, $msg );
152 * Add warnings and errors from a StatusValue object to the result
153 * @param string|null $modulePath
154 * @param StatusValue $status
155 * @param string[]|string $types 'warning' and/or 'error'
157 public function addMessagesFromStatus(
158 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ]
160 if ( $status->isGood() ||
!$status->getErrors() ) {
164 $types = (array)$types;
165 foreach ( $status->getErrors() as $error ) {
166 if ( !in_array( $error['type'], $types, true ) ) {
170 if ( $error['type'] === 'error' ) {
173 // Assume any unknown type is a warning
177 $msg = ApiMessage
::create( $error )
178 ->inLanguage( $this->lang
)
179 ->title( $this->getDummyTitle() )
180 ->useDatabase( $this->useDB
);
181 $this->addWarningOrError( $tag, $modulePath, $msg );
186 * Get an ApiMessage from an exception
188 * @param Exception|Throwable $exception
189 * @param array $options
190 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
191 * message if it's not an ILocalizedException. The exception's message
192 * will be added as the final parameter.
193 * - code: (string) Default code
194 * - data: (array) Default extra data
195 * @return IApiMessage
197 public function getMessageFromException( $exception, array $options = [] ) {
198 $options +
= [ 'code' => null, 'data' => [] ];
200 if ( $exception instanceof ILocalizedException
) {
201 $msg = $exception->getMessageObject();
203 } elseif ( $exception instanceof MessageSpecifier
) {
204 $msg = Message
::newFromSpecifier( $exception );
207 if ( isset( $options['wrap'] ) ) {
208 $msg = $options['wrap'];
210 $msg = new RawMessage( '$1' );
211 if ( !isset( $options['code'] ) ) {
212 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
213 $options['code'] = 'internal_api_error_' . $class;
216 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
218 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
220 ->inLanguage( $this->lang
)
221 ->title( $this->getDummyTitle() )
222 ->useDatabase( $this->useDB
);
226 * Format an exception as an array
228 * @param Exception|Throwable $exception
229 * @param array $options See self::getMessageFromException(), plus
230 * - format: (string) Format override
233 public function formatException( $exception, array $options = [] ) {
234 return $this->formatMessage(
235 $this->getMessageFromException( $exception, $options ),
236 $options['format'] ??
null
241 * Format a message as an array
242 * @param Message|array|string $msg Message. See ApiMessage::create().
243 * @param string|null $format
246 public function formatMessage( $msg, $format = null ) {
247 $msg = ApiMessage
::create( $msg )
248 ->inLanguage( $this->lang
)
249 ->title( $this->getDummyTitle() )
250 ->useDatabase( $this->useDB
);
251 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
255 * Format messages from a StatusValue as an array
256 * @param StatusValue $status
257 * @param string $type 'warning' or 'error'
258 * @param string|null $format
261 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
262 if ( $status->isGood() ||
!$status->getErrors() ) {
266 $result = new ApiResult( 1e6
);
267 $formatter = new ApiErrorFormatter(
268 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
270 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
273 return (array)$result->getResultData( [ 'errors' ] );
275 return (array)$result->getResultData( [ 'warnings' ] );
280 * Turn wikitext into something resembling plaintext
282 * @param string $text
285 public static function stripMarkup( $text ) {
286 // Turn semantic quoting tags to quotes
287 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
289 // Strip tags and decode.
290 $ret = Sanitizer
::stripAllTags( $ret );
296 * Format a Message object for raw format
297 * @param MessageSpecifier $msg
300 private function formatRawMessage( MessageSpecifier
$msg ) {
302 'key' => $msg->getKey(),
303 'params' => $msg->getParams(),
305 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
307 // Transform Messages as parameters in the style of Message::fooParam().
308 foreach ( $ret['params'] as $i => $param ) {
309 if ( $param instanceof MessageSpecifier
) {
310 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
317 * Format a message as an array
319 * @param ApiMessage|ApiRawMessage $msg
320 * @param string|null $format
323 protected function formatMessageInternal( $msg, $format ) {
324 $value = [ 'code' => $msg->getApiCode() ];
328 'text' => self
::stripMarkup( $msg->text() ),
329 ApiResult
::META_CONTENT
=> 'text',
335 'text' => $msg->text(),
336 ApiResult
::META_CONTENT
=> 'text',
342 'html' => $msg->parse(),
343 ApiResult
::META_CONTENT
=> 'html',
348 $value +
= $this->formatRawMessage( $msg );
354 $data = $msg->getApiData();
356 $value['data'] = $msg->getApiData() +
[
357 ApiResult
::META_TYPE
=> 'assoc',
364 * Actually add the warning or error to the result
365 * @param string $tag 'warning' or 'error'
366 * @param string|null $modulePath
367 * @param ApiMessage|ApiRawMessage $msg
369 protected function addWarningOrError( $tag, $modulePath, $msg ) {
370 $value = $this->formatMessageInternal( $msg, $this->format
);
371 if ( $modulePath !== null ) {
372 $value +
= [ 'module' => $modulePath ];
375 $path = [ $tag . 's' ];
376 $existing = $this->result
->getResultData( $path );
377 if ( $existing === null ||
!in_array( $value, $existing ) ) {
378 $flags = ApiResult
::NO_SIZE_CHECK
;
379 if ( $existing === null ) {
380 $flags |
= ApiResult
::ADD_ON_TOP
;
382 $this->result
->addValue( $path, null, $value, $flags );
383 $this->result
->addIndexedTagName( $path, $tag );
389 * Format errors and warnings in the old style, for backwards compatibility.
391 * @deprecated Only for backwards compatibility, do not use
394 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
395 class ApiErrorFormatter_BackCompat
extends ApiErrorFormatter
{
398 * @param ApiResult $result Into which data will be added
400 public function __construct( ApiResult
$result ) {
401 parent
::__construct( $result, Language
::factory( 'en' ), 'none', false );
404 public function getFormat() {
408 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
409 if ( $status->isGood() ||
!$status->getErrors() ) {
414 foreach ( $status->getErrorsByType( $type ) as $error ) {
415 $msg = ApiMessage
::create( $error );
417 'message' => $msg->getKey(),
418 'params' => $msg->getParams(),
419 'code' => $msg->getApiCode(),
421 ApiResult
::setIndexedTagName( $error['params'], 'param' );
424 ApiResult
::setIndexedTagName( $result, $type );
429 protected function formatMessageInternal( $msg, $format ) {
431 'code' => $msg->getApiCode(),
432 'info' => $msg->text(),
433 ] +
$msg->getApiData();
437 * Format an exception as an array
439 * @param Exception|Throwable $exception
440 * @param array $options See parent::formatException(), plus
441 * - bc: (bool) Return only the string, not an array
442 * @return array|string
444 public function formatException( $exception, array $options = [] ) {
445 $ret = parent
::formatException( $exception, $options );
446 return empty( $options['bc'] ) ?
$ret : $ret['info'];
449 protected function addWarningOrError( $tag, $modulePath, $msg ) {
450 $value = self
::stripMarkup( $msg->text() );
452 if ( $tag === 'error' ) {
453 // In BC mode, only one error
454 $existingError = $this->result
->getResultData( [ 'error' ] );
455 if ( !is_array( $existingError ) ||
456 !isset( $existingError['code'] ) ||
!isset( $existingError['info'] )
459 'code' => $msg->getApiCode(),
461 ] +
$msg->getApiData();
462 $this->result
->addValue( null, 'error', $value,
463 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
466 if ( $modulePath === null ) {
467 $moduleName = 'unknown';
469 $i = strrpos( $modulePath, '+' );
470 $moduleName = $i === false ?
$modulePath : substr( $modulePath, $i +
1 );
473 // Don't add duplicate warnings
475 $path = [ $tag, $moduleName ];
476 $oldWarning = $this->result
->getResultData( [ $tag, $moduleName, $tag ] );
477 if ( $oldWarning !== null ) {
478 $warnPos = strpos( $oldWarning, $value );
479 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
480 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
481 // Check if $value is followed by "\n" or the end of the $oldWarning
482 $warnPos +
= strlen( $value );
483 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
487 // If there is a warning already, append it to the existing one
488 $value = "$oldWarning\n$value";
490 $this->result
->addContentValue( $path, $tag, $value,
491 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);