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'
156 * @param string[] $filter Messages to filter out (since 1.33)
158 public function addMessagesFromStatus(
159 $modulePath, StatusValue
$status, $types = [ 'warning', 'error' ], array $filter = []
161 if ( $status->isGood() ||
!$status->getErrors() ) {
165 $types = (array)$types;
166 foreach ( $status->getErrors() as $error ) {
167 if ( !in_array( $error['type'], $types, true ) ) {
171 if ( $error['type'] === 'error' ) {
174 // Assume any unknown type is a warning
178 $msg = ApiMessage
::create( $error )
179 ->inLanguage( $this->lang
)
180 ->title( $this->getDummyTitle() )
181 ->useDatabase( $this->useDB
);
182 if ( !in_array( $msg->getKey(), $filter, true ) ) {
183 $this->addWarningOrError( $tag, $modulePath, $msg );
189 * Get an ApiMessage from an exception
191 * @param Exception|Throwable $exception
192 * @param array $options
193 * - wrap: (string|array|MessageSpecifier) Used to wrap the exception's
194 * message if it's not an ILocalizedException. The exception's message
195 * will be added as the final parameter.
196 * - code: (string) Default code
197 * - data: (array) Default extra data
198 * @return IApiMessage
200 public function getMessageFromException( $exception, array $options = [] ) {
201 $options +
= [ 'code' => null, 'data' => [] ];
203 if ( $exception instanceof ILocalizedException
) {
204 $msg = $exception->getMessageObject();
206 } elseif ( $exception instanceof MessageSpecifier
) {
207 $msg = Message
::newFromSpecifier( $exception );
210 if ( isset( $options['wrap'] ) ) {
211 $msg = $options['wrap'];
213 $msg = new RawMessage( '$1' );
214 if ( !isset( $options['code'] ) ) {
215 $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $exception ) );
216 $options['code'] = 'internal_api_error_' . $class;
217 $options['data']['errorclass'] = get_class( $exception );
220 $params = [ wfEscapeWikiText( $exception->getMessage() ) ];
222 return ApiMessage
::create( $msg, $options['code'], $options['data'] )
224 ->inLanguage( $this->lang
)
225 ->title( $this->getDummyTitle() )
226 ->useDatabase( $this->useDB
);
230 * Format an exception as an array
232 * @param Exception|Throwable $exception
233 * @param array $options See self::getMessageFromException(), plus
234 * - format: (string) Format override
237 public function formatException( $exception, array $options = [] ) {
238 return $this->formatMessage(
239 $this->getMessageFromException( $exception, $options ),
240 $options['format'] ??
null
245 * Format a message as an array
246 * @param Message|array|string $msg Message. See ApiMessage::create().
247 * @param string|null $format
250 public function formatMessage( $msg, $format = null ) {
251 $msg = ApiMessage
::create( $msg )
252 ->inLanguage( $this->lang
)
253 ->title( $this->getDummyTitle() )
254 ->useDatabase( $this->useDB
);
255 return $this->formatMessageInternal( $msg, $format ?
: $this->format
);
259 * Format messages from a StatusValue as an array
260 * @param StatusValue $status
261 * @param string $type 'warning' or 'error'
262 * @param string|null $format
265 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
266 if ( $status->isGood() ||
!$status->getErrors() ) {
270 $result = new ApiResult( 1e6
);
271 $formatter = new ApiErrorFormatter(
272 $result, $this->lang
, $format ?
: $this->format
, $this->useDB
274 $formatter->addMessagesFromStatus( null, $status, [ $type ] );
277 return (array)$result->getResultData( [ 'errors' ] );
279 return (array)$result->getResultData( [ 'warnings' ] );
284 * Turn wikitext into something resembling plaintext
286 * @param string $text
289 public static function stripMarkup( $text ) {
290 // Turn semantic quoting tags to quotes
291 $ret = preg_replace( '!</?(var|kbd|samp|code)>!', '"', $text );
293 // Strip tags and decode.
294 $ret = Sanitizer
::stripAllTags( $ret );
300 * Format a Message object for raw format
301 * @param MessageSpecifier $msg
304 private function formatRawMessage( MessageSpecifier
$msg ) {
306 'key' => $msg->getKey(),
307 'params' => $msg->getParams(),
309 ApiResult
::setIndexedTagName( $ret['params'], 'param' );
311 // Transform Messages as parameters in the style of Message::fooParam().
312 foreach ( $ret['params'] as $i => $param ) {
313 if ( $param instanceof MessageSpecifier
) {
314 $ret['params'][$i] = [ 'message' => $this->formatRawMessage( $param ) ];
321 * Format a message as an array
323 * @param ApiMessage|ApiRawMessage $msg
324 * @param string|null $format
327 protected function formatMessageInternal( $msg, $format ) {
328 $value = [ 'code' => $msg->getApiCode() ];
332 'text' => self
::stripMarkup( $msg->text() ),
333 ApiResult
::META_CONTENT
=> 'text',
339 'text' => $msg->text(),
340 ApiResult
::META_CONTENT
=> 'text',
346 'html' => $msg->parse(),
347 ApiResult
::META_CONTENT
=> 'html',
352 $value +
= $this->formatRawMessage( $msg );
358 $data = $msg->getApiData();
360 $value['data'] = $msg->getApiData() +
[
361 ApiResult
::META_TYPE
=> 'assoc',
368 * Actually add the warning or error to the result
369 * @param string $tag 'warning' or 'error'
370 * @param string|null $modulePath
371 * @param ApiMessage|ApiRawMessage $msg
373 protected function addWarningOrError( $tag, $modulePath, $msg ) {
374 $value = $this->formatMessageInternal( $msg, $this->format
);
375 if ( $modulePath !== null ) {
376 $value +
= [ 'module' => $modulePath ];
379 $path = [ $tag . 's' ];
380 $existing = $this->result
->getResultData( $path );
381 if ( $existing === null ||
!in_array( $value, $existing ) ) {
382 $flags = ApiResult
::NO_SIZE_CHECK
;
383 if ( $existing === null ) {
384 $flags |
= ApiResult
::ADD_ON_TOP
;
386 $this->result
->addValue( $path, null, $value, $flags );
387 $this->result
->addIndexedTagName( $path, $tag );
393 * Format errors and warnings in the old style, for backwards compatibility.
395 * @deprecated Only for backwards compatibility, do not use
398 // phpcs:ignore Squiz.Classes.ValidClassName.NotCamelCaps
399 class ApiErrorFormatter_BackCompat
extends ApiErrorFormatter
{
402 * @param ApiResult $result Into which data will be added
404 public function __construct( ApiResult
$result ) {
405 parent
::__construct( $result, Language
::factory( 'en' ), 'none', false );
408 public function getFormat() {
412 public function arrayFromStatus( StatusValue
$status, $type = 'error', $format = null ) {
413 if ( $status->isGood() ||
!$status->getErrors() ) {
418 foreach ( $status->getErrorsByType( $type ) as $error ) {
419 $msg = ApiMessage
::create( $error );
421 'message' => $msg->getKey(),
422 'params' => $msg->getParams(),
423 'code' => $msg->getApiCode(),
425 ApiResult
::setIndexedTagName( $error['params'], 'param' );
428 ApiResult
::setIndexedTagName( $result, $type );
433 protected function formatMessageInternal( $msg, $format ) {
435 'code' => $msg->getApiCode(),
436 'info' => $msg->text(),
437 ] +
$msg->getApiData();
441 * Format an exception as an array
443 * @param Exception|Throwable $exception
444 * @param array $options See parent::formatException(), plus
445 * - bc: (bool) Return only the string, not an array
446 * @return array|string
448 public function formatException( $exception, array $options = [] ) {
449 $ret = parent
::formatException( $exception, $options );
450 return empty( $options['bc'] ) ?
$ret : $ret['info'];
453 protected function addWarningOrError( $tag, $modulePath, $msg ) {
454 $value = self
::stripMarkup( $msg->text() );
456 if ( $tag === 'error' ) {
457 // In BC mode, only one error
458 $existingError = $this->result
->getResultData( [ 'error' ] );
459 if ( !is_array( $existingError ) ||
460 !isset( $existingError['code'] ) ||
!isset( $existingError['info'] )
463 'code' => $msg->getApiCode(),
465 ] +
$msg->getApiData();
466 $this->result
->addValue( null, 'error', $value,
467 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);
470 if ( $modulePath === null ) {
471 $moduleName = 'unknown';
473 $i = strrpos( $modulePath, '+' );
474 $moduleName = $i === false ?
$modulePath : substr( $modulePath, $i +
1 );
477 // Don't add duplicate warnings
479 $path = [ $tag, $moduleName ];
480 $oldWarning = $this->result
->getResultData( [ $tag, $moduleName, $tag ] );
481 if ( $oldWarning !== null ) {
482 $warnPos = strpos( $oldWarning, $value );
483 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
484 if ( $warnPos !== false && ( $warnPos === 0 ||
$oldWarning[$warnPos - 1] === "\n" ) ) {
485 // Check if $value is followed by "\n" or the end of the $oldWarning
486 $warnPos +
= strlen( $value );
487 if ( strlen( $oldWarning ) <= $warnPos ||
$oldWarning[$warnPos] === "\n" ) {
491 // If there is a warning already, append it to the existing one
492 $value = "$oldWarning\n$value";
494 $this->result
->addContentValue( $path, $tag, $value,
495 ApiResult
::OVERRIDE | ApiResult
::ADD_ON_TOP | ApiResult
::NO_SIZE_CHECK
);